JSON.stringify() method and JSON.parse() method

JSON.stringify() and  JSON.parse() are a pair of methods for processing JSON data. The former serializes JSON objects into strings, while the latter parses JSON strings into JSON objects.

 Basic usage

JSON.stringify()

Use: JSON.stringify(value, ?replacer, ?space)

parameter:

value, is the data object that needs to be serialized;

replacer, the object attribute to be processed, optional;

space, the format after serialization, can be positive integer or string, optional.

value

This parameter is a secure JSON object that needs to be stringified, and an unsafe JSON object cannot be serialized normally.

undefined、function、symbolObjects and objects containing circular references do not conform to the JSON structure standard, so they and the objects containing them are unsafe JSON objects.

  • undefined, function, symbol and contained unsafe JSON objects

For undefined, function, symbol and contained unsafe JSON objects,JSON.stringify()会返回 undefined

// undefined、function、symbol、及包含关系
JSON.stringify(Symbol()); // undefined
// 包含它们的对象,自动将其忽略
JSON.stringify({a:1, b:undefined, c:function(){}, [Symbol()]:1}); // '{"a":1}'
// 包含它们的数组,自动将其转成null
JSON.stringify([1,undefined,function(){},Symbol()]);    //  '[1,null,null,null]'
  • Objects containing circular references

If there are mutual references between multiple objects, an infinite loop will be formed, and an error will be reported when JSON serializes these two objects.

let o1={};
let o2={a:o1};
o1.a=o2
JSON.stringify(o1);  //  Uncaught TypeError
JSON.stringify(o2);  //  Uncaught TypeError
  • object with toJSON()methods

For objects containing toJSON(), toJSON() will be called first, then its value will be serialized, and the serialization of other properties will be ignored.

var obj = {
  a: 1,
  toJSON(){
    return [Symbol(),function(){},1]
  }
};
JSON.stringify(obj); // '[null,null,1]'

replacer

It is used to specify the attributes that need to be processed during object serialization, which can be a string array or a function.

when it is an array:

var obj={a:1,b:2,c:3};
JSON.stringify(obj,['c']); // '{"c":3}'

when it's a function:

The function will first call the object itself, and then iterate through each property of the object. The function passes in two parameters, the first is the attribute name (key), and the second is the attribute value (value). When starting to call the object itself, the first parameter key is an empty string, and the second parameter value is the object itself, and at this time the return value of the function will directly replace the original object. Then every time the object property is traversed, the return value will replace the original value of the property.

var obj = {a: 1,b: 2};
JSON.stringify(obj, function(key,value){
  if(key === '') { return {a:1,c:2} }  // 替换原对象为{a:1,c:2}
  if(key === 'a') { return undefined }  // 替换原有属性a的值为undefined,最终该属性会被忽略
  if(key === 'b') { return 'bbb' }  // 原对象已被替换,所以不存在属性b
  if(key === 'c') { return 'ccc' }  // 替换原有属性c的值为'ccc'
});   //  "{"c":"ccc"}"

space:

Specifies the indentation format for the output string. space can be a positive integer or a string. When it is a positive integer, it specifies the number of characters for each level of indentation; when it is a string, the first ten characters of the string will be used for each level of indentation (padding).

var obj={a:1,b:2,c:3};
JSON.stringify(obj,undefined,4); 
// '{\n    "a": 1,\n    "b": 2,\n    "c": 3\n}'
JSON.stringify(obj,undefined,"1234567890!@#$%^&*"); 
// '{\n1234567890"a": 1,\n1234567890"b": 2,\n1234567890"c": 3\n}'

JSON.parse()

Use: JSON.parse(text, ?reviver)

parameter:

text, the JSON string to be parsed;

reviver, function, used to revise the original value generated by parsing, optional.

text

The parameter must be a string that conforms to the JSON specification. If it is another type, it will be converted into a string format. If it does not conform to the JSON specification, the key in the JSON string does not have double quotes (single quotes are not acceptable), then Will report an error.

JSON.parse('[1,2]');  // [1,2]
JSON.parse('null');  // null
JSON.parse('false');  // false
JSON.parse('{"a":1}');  // {a: 1}
JSON.parse('{a:1}');  // Uncaught SyntaxError
JSON.parse("{'a':1}");  // Uncaught SyntaxError
JSON.parse('undefined');  // Uncaught SyntaxError
JSON.parse(()=>{console.log('parse')}); // Uncaught SyntaxError
JSON.parse(true);  // true ,text先被强制转换成了字符串形式
JSON.parse(3);  // 3

revive

This parameter is a function, which is similar JSON.stringify()to the second parameter replacer, which also traverses and processes attributes, and also has two parameters key and value.

let json_str='{"k1":1,"k2":2,"k3":3}';
JSON.parse(json_str,function(key,value){
    if(key === "k1") {
        return function(){}
    }
    if(key === "k2") { 
        console.log(value) // 2
        return 'k1-'+ value
   }
   if(key === 'k3') { 
        console.log(value) // 3
        return 'k3-value'
   }
   if(key === '') { 
        console.log(value) // {k2: 'k1-2', k3: 'k3-value', k1: ƒ}
        return value // {k1:1,k2:2,k3:3}
  }
}); // {k2: 'k1-2', k3: 'k3-value', k1: ƒ}

Summarize:

① Separate stringification undefined、functionand symbolresults are both undefined;
② Stringify the object containing undefined、functionand symbol, the properties where these values ​​are located will be ignored;
③ Stringify the array containing undefined、functionand symbol, these values ​​will be converted to null;
④ Stringization contains loops The referenced object will report an error;
⑤ When stringifying toJSON()an object with a method, the return value of the method execution will be directly stringified;
⑥The JSON.stringify()three parameters are used to specify the object that needs to be The properties to be processed and the indentation format of the specified output string ; The two parameters of
⑦ are used to specify the string to be parsed and modify the original value generated by the parsing .JSON.parse()


For more details, please refer to: https://www.jianshu.com/p/7b320be863de

Guess you like

Origin blog.csdn.net/qq_58062502/article/details/129040732