日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JSON.Stringify

發布時間:2023/12/10 javascript 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JSON.Stringify 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

JSON.stringify 是日常開發中經常用到的 JSON 對象中的一個方法,JSON 對象包含兩個方法:一是用于解析成 JSON 對象的 parse();二是用于將對象轉換為 JSON 字符串方法的 stringify()

JSON.parse
【參考鏈接: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse】

JSON.parse() 方法用來解析JSON字符串,構造由字符串描述的JavaScript值或對象。提供可選的 reviver 函數用以在返回之前對所得到的對象執行變換(操作)。

const json = '{"result":true, "count":42}'; const obj = JSON.parse(json);console.log(obj.count); // expected output: 42console.log(obj.result); // expected output: true ------- JSON.parse('{"p": 5}', function (k, v) {if(k === '') return v; // 如果到了最頂層,則直接返回屬性值,return v * 2; // 否則將屬性值變為原來的 2 倍。 }); // { p: 10 }

JSON.stringify
【參考鏈接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify】

JSON.stringify 方法是將一個 JavaScript 對象或值轉換為 JSON 字符串,默認該方法其實有三個參數:第一個參數是必選,后面兩個是可選參數非必選。第一個參數傳入的是要轉換的對象;第二個是一個 replacer 函數,比如指定的 replacer 是數組,則可選擇性地僅處理包含數組指定的屬性;第三個參數用來控制結果字符串里面的間距,后面兩個參數整體用得比較少。

JSON.stringify({ x: 1, y: 2 }); // "{"x":1,"y":2}" JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }) // "{"x":[10,null,null,null]}" /* 第二個參數的例子 */ function replacer(key, value) {if (typeof value === "string") {return undefined;}return value; } var foo = {foundation: "Mozilla", model: "box", week: 4, transport: "car", month: 7}; var jsonString = JSON.stringify(foo, replacer); console.log(jsonString); // "{"week":4,"month":7}" /* 第三個參數的例子 */ JSON.stringify({ a: 2 }, null, " "); /* "{"a": 2 }"*/ JSON.stringify({ a: 2 }, null, ""); // "{"a":2}"

手動實現一個JSON.Stringify

function jsonStringify(data) {let type = typeof data;if(type !== 'object') {let result = data;//data 可能是基礎數據類型的情況在這里處理if (Number.isNaN(data) || data === Infinity) {//NaN 和 Infinity 序列化返回 "null"result = "null";} else if (type === 'function' || type === 'undefined' || type === 'symbol') {// 由于 function 序列化返回 undefined,因此和 undefined、symbol 一起處理return undefined;} else if (type === 'string') {result = '"' + data + '"';}return String(result);} else if (type === 'object') {if (data === null) {return "null" // 第01講有講過 typeof null 為'object'的特殊情況} else if (data.toJSON && typeof data.toJSON === 'function') {return jsonStringify(data.toJSON());} else if (data instanceof Array) {let result = [];//如果是數組,那么數組里面的每一項類型又有可能是多樣的data.forEach((item, index) => {if (typeof item === 'undefined' || typeof item === 'function' || typeof item === 'symbol') {result[index] = "null";} else {result[index] = jsonStringify(item);}});result = "[" + result + "]";return result.replace(/'/g, '"');} else {// 處理普通對象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, '"');}} }

測試:

let nl = null; console.log(jsonStringify(nl) === JSON.stringify(nl)); // true let und = undefined; console.log(jsonStringify(undefined) === JSON.stringify(undefined)); // true let boo = false; console.log(jsonStringify(boo) === JSON.stringify(boo)); // true let nan = NaN; console.log(jsonStringify(nan) === JSON.stringify(nan)); // true let inf = Infinity; console.log(jsonStringify(Infinity) === JSON.stringify(Infinity)); // true let str = "jack"; console.log(jsonStringify(str) === JSON.stringify(str)); // true let reg = new RegExp("\w"); console.log(jsonStringify(reg) === JSON.stringify(reg)); // true let date = new Date(); console.log(jsonStringify(date) === JSON.stringify(date)); // true let sym = Symbol(1); console.log(jsonStringify(sym) === JSON.stringify(sym)); // true let array = [1,2,3]; console.log(jsonStringify(array) === JSON.stringify(array)); // true let obj = {name: 'jack',age: 18,attr: ['coding', 123],date: new Date(),uni: Symbol(2),sayHi: function() {console.log("hi")},info: {sister: 'lily',age: 16,intro: {money: undefined,job: null}} } console.log(jsonStringify(obj) === JSON.stringify(obj)); // true

注:

  • 由于 function 返回 ‘null’, 并且 typeof function 能直接返回精確的判斷,故在整體邏輯處理基礎數據類型的時候,會隨著 undefined,symbol 直接處理了;
  • 由于 typeof null 的時候返回’object’,故 null 的判斷邏輯整體在處理引用數據類型的邏輯里面;
  • 關于引用數據類型中的數組,由于數組的每一項的數據類型又有很多的可能性,故在處理數組過程中又將 undefined,symbol,function 作為數組其中一項的情況做了特殊處理;
  • 同樣在最后處理普通對象的時候,key (鍵值)也存在和數組一樣的問題,故又需要再針對上面這幾種情況(undefined,symbol,function)做特殊處理;
  • 最后在處理普通對象過程中,對于循環引用的問題暫未做檢測,如果是有循環引用的情況,需要拋出 Error;
  • 根據官方給出的 JSON.stringify 的第二個以及第三個參數的實現,本段模擬實現的代碼并未實現
  • 總結

    以上是生活随笔為你收集整理的JSON.Stringify的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。