JSON.stringify()方法 和 JSON.parse()方法

JSON.stringify() 和 JSON.parse() 是一对处理JSON数据的方法,前者是将JSON对象序列化为字符串,而后者是将JSON字符串解析为JSON对象。

 基本使用方法

JSON.stringify()

使用:JSON.stringify(value, ?replacer , ?space)

参数:

value,为需要序列化的数据对象;

replacer,需要处理的对象属性,可选;

space,序列化之后的格式,可为正整数或字符串,可选。

value

该参数是需要字符串化且安全的JSON对象,不安全的JSON对象将不能被正常序列化。

undefined、function、symbol和包含循环的引用的对象都不符合JSON结构标准,故它们本身以及包含它们的对象都是不安全的JSON对象。

  • undefined、function、symbol及包含的不安全的JSON对象

对于undefined、function、symbol及包含的不安全的JSON对象,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]'
  • 包含循环引用的对象

如量对象存在相互引用,会形成一个无限循环,JSON序列化这两个对象都会报错。

let o1={};
let o2={a:o1};
o1.a=o2
JSON.stringify(o1);  //  Uncaught TypeError
JSON.stringify(o2);  //  Uncaught TypeError
  • 含有toJSON()方法的对象

如含有toJSON()的对象,会先调用toJSON(),然对其值序列化,并忽略其他属性的序列化。

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

replacer

用于指定对象序列化过程中需要被处理的属性,它可为字符串数组或函数。

当它为数组时:

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

当它是函数时:

该函数会先调用对象本身,然后遍历对象的每个属性。函数传入两个参数,第一个为属性名(key),第二个为属性值(value)。开始调用对象本身时,第一个参数key为空字符串,第二个参数value为对象本身,而此时函数的返回值会直接替换原对象。而后每次遍历对象属性时的返回值都会替换原有该属性的值。

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 output strings. 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

おすすめ

転載: blog.csdn.net/qq_58062502/article/details/129040732