javascript
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注:
總結
以上是生活随笔為你收集整理的JSON.Stringify的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PMP 学习总结
- 下一篇: webstorm破解码