簡易版本JSON.stringify的實現(xiàn)及其六大特性詳解
前言
JSON.stringify是一個使用非常高頻的API,但是其卻存在一個特性,我們在使用的過程中需要留意這些特性以避免為代碼程序埋雷,那么接下來便一起動手實現(xiàn)一個簡易版本的jsonStringify函數(shù)
JSON.stringify六大特性
特性一
布爾值、數(shù)字、字符串的包裝對象在序列化過程中會自動轉(zhuǎn)換成對應(yīng)的原始值
現(xiàn)在有這么一個對象:
const obj = { bol: new Boolean(true), num: new Number(1), str: new String(1) }
利用typeof檢測obj各個屬性的數(shù)據(jù)類型
typeof obj.bol; // object typeof obj.num; // object typeof obj.str; // object
將其序列化stringify之后
JSON.stringify(obj); // {"bol":true,"num":1,"str":"1"}
此時再將其解析parse進行各個屬性的數(shù)據(jù)類型
const stringifyObj = JSON.parse(JSON.stringify(obj)); typeof stringifyObj.bol; // boolean typeof stringifyObj.num; // number typeof stringifyObj.str; // string
特性二
NaN、Infinity、-Infinity以及null在序列化stringify時都會被當(dāng)作null
const obj = { nan: NaN, infinity: Infinity, null: null, }; JSON.stringify(obj); // {"nan":null,"infinity":null,"null":null}
特性三
對象在序列化的時候,若是其存在toJSON函數(shù),這個函數(shù)返回的值就是整個對象序列化后的結(jié)果
const obj = { nan: NaN, infinity: Infinity, null: null, toJSON() { return "擁有toJSON函數(shù)"; }, }; JSON.stringify(obj); // "擁有toJSON函數(shù)"
可以看到序列化之后的數(shù)據(jù)僅存在toJSON函數(shù)的返回值,其余數(shù)據(jù)全部忽略
⚠️:Date數(shù)據(jù)會被正常序列化,因為Date上部署了toJSON函數(shù),可以通過控制臺打印Date.prototype.toJSON得知
const obj = { date: new Date(), }; JSON.stringify(obj); // {"date":"2021-10-08T11:43:31.881Z"}
特性四
表現(xiàn)不一的undefined、function和symbol
作為對象鍵值對時:
作為值:
const obj = { undefined: undefined, fn() {}, symbol: Symbol() }; JSON.stringify(obj); // {}
作為鍵:
const fn = function () {}; const obj = { [undefined]: undefined, [fn]: function () {}, [Symbol()]: Symbol() }; JSON.stringify(obj); // {}
undefined、function和symbol作為對象的key和value時,會在序列化時將其忽略
⚠️:此時可能會改變對象原有的順序,因為上述三種數(shù)據(jù)會在序列化時被忽略
作為數(shù)組值時:
const arr = [undefined, function fn() {}, Symbol()]; JSON.stringify(arr); // [null,null,null]
undefined、function和symbol作為數(shù)組的value時,會在序列化時將其都轉(zhuǎn)換為null
單獨存在時:
JSON.stringify(undefined); // undefined JSON.stringify(function () {}); // undefined JSON.stringify(Symbol()); // undefined
undefined、function和symbol單獨存在時,會在序列化時都轉(zhuǎn)換為undefined
特性五
序列化過程中,僅會序列化可枚舉屬性,不可枚舉屬性將會忽視
const obj = { name: "nordon", age: 18, }; // 將age修改為不可枚舉屬性 Object.defineProperty(obj, "age", { enumerable: false, }); JSON.stringify(obj); // {"name":"nordon"}
⚠️:此舉也會改變對象的原有順序
特性六
循環(huán)引用的對象,會在序列化時拋出異常
const obj = { name: "nordon", age: 18, }; const p = { name: 'wy', obj } obj.p = p JSON.stringify(obj);
此時會導(dǎo)致控制臺拋出異常:
Uncaught TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' | property 'p' -> object with constructor 'Object' --- property 'obj' closes the circle at JSON.stringify (<anonymous>)
手動實現(xiàn)stringify
明白了JSON.stringify的一些特性,接下來便可以依據(jù)這些特性動手實現(xiàn)一個kack版本
在動手實現(xiàn)之前,先利用柯里化封裝一些數(shù)據(jù)類型校驗的工具函數(shù):
const currying = (fn, ...outParams) => { // 獲取 fn 函數(shù)需要的參數(shù)個數(shù) const paramsLen = fn.length; return (...args) => { // 收集全部參數(shù) let params = [...outParams, ...args]; // 若參數(shù)沒有達(dá)到 fn 需要的參數(shù),繼續(xù)收集參數(shù) if (params.length < paramsLen) { return currying(fn, ...params); } return fn(...params); }; }; /** * type: 類型 - [object Array]、[object Number]等 * source: 數(shù)據(jù)源 */ const judgeType = (type, source) => { return Object.prototype.toString.call(source) === type; }; const isUndefined = currying(judgeType, "[object Undefined]"); const isSymbol = currying(judgeType, "[object Symbol]"); const isFunction = currying(judgeType, "[object Function]"); const isObject = currying(judgeType, "[object Object]"); const isNull = currying(judgeType, "[object Null]");
下面直接上代碼:
function jsonStringify(data) { let type = typeof data; if (isNull(data)) { // null 直接返回 字符串'null' return "null"; } else if (data.toJSON && typeof data.toJSON === "function") { // 配置了 toJSON函數(shù), 直接使用 toJSON 返回的數(shù)據(jù)且忽略其他數(shù)據(jù) return jsonStringify(data.toJSON()); } else if (Array.isArray(data)) { let result = []; //如果是數(shù)組,那么數(shù)組里面的每一項類型又有可能是多樣的 data.forEach((item, index) => { if (isUndefined(item) || isSymbol(item) || isFunction(item)) { result[index] = "null"; } else { result[index] = jsonStringify(item); } }); result = "[" + result + "]"; return result.replace(/'/g, '"'); } else if (isObject(data)) { // 處理普通對象 let result = []; Object.keys(data).forEach((item, index) => { if (typeof item !== "symbol") { //key 如果是 symbol 對象,忽略 if ( data[item] !== undefined && typeof data[item] !== "function" && typeof data[item] !== "symbol" ) { //鍵值如果是 undefined、function、symbol 為屬性值,忽略 result.push( '"' + item + '"' + ":" + jsonStringify(data[item]) ); } } }); return ("{" + result + "}").replace(/'/g, '"'); } else if (type !== "object") { let result = data; //data 可能是基礎(chǔ)數(shù)據(jù)類型的情況在這里處理 if (Number.isNaN(data) || data === Infinity) { //NaN 和 Infinity 序列化返回 "null" result = "null"; } else if (isUndefined(data) || isSymbol(data) || isFunction(data)) { // 由于 function 序列化返回 undefined,因此和 undefined、symbol 一起處理 return undefined; } else if (type === "string") { result = '"' + data + '"'; } return String(result); } }
至此簡易版本的JSON.stringify完成,雖然能力尚欠缺許多,主要是提供一個思路,核心注釋已注釋在代碼中,可結(jié)合代碼和上文的特性一起理解
總結(jié)
到此這篇關(guān)于JSON.stringify實現(xiàn)及其六大特性詳解的文章就介紹到這了,更多相關(guān)簡易版本JSON.stringify及特性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- JS中JSON.parse(JSON.stringify())實現(xiàn)深拷貝
- JavaScript語法 JSON序列化之stringify實例詳解
- JS中的Error對象及使用JSON.stringify()序列化Error問題
- JSON stringify及parse方法實現(xiàn)數(shù)據(jù)深拷貝
- JavaScript對象與JSON格式的轉(zhuǎn)換及JSON.stringify和JSON.parse的使用方法
- 前端使用JSON.stringify實現(xiàn)深拷貝的巨坑詳解
- 學(xué)習(xí)JSON.stringify的9大特性和轉(zhuǎn)換規(guī)則
- 詳解JSON.parse和JSON.stringify用法
- JSON.stringify的多種用法總結(jié)
- 使用 JSON.stringify() 列化一個Error
相關(guān)文章
javascript實現(xiàn)禁止復(fù)制網(wǎng)頁內(nèi)容
這篇文章主要介紹了javascript實現(xiàn)禁止復(fù)制網(wǎng)頁內(nèi)容,需要的朋友可以參考下2014-12-12微信小程序?qū)崿F(xiàn)圖片翻轉(zhuǎn)效果的實例代碼
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)圖片翻轉(zhuǎn)效果的實例代碼,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09BootStrap表單控件之復(fù)選框checkbox和單選擇按鈕radio
這篇文章主要介紹了BootStrap表單控件之復(fù)選框checkbox和單選擇按鈕radio的相關(guān)資料,需要的朋友可以參考下2017-05-05uniapp中使用?uni.navigateBack()?返回上級頁面并傳參的方法
最近遇到這樣的需求在A頁面中通過跳轉(zhuǎn)到B頁面,在B頁面中處理的數(shù)據(jù),需要跳轉(zhuǎn)回A頁面供其使用,本文給大家分享uniapp中使用?uni.navigateBack()?返回上級頁面并傳參的操作方法,感興趣的朋友一起看看吧2023-10-10