JSON.stingify() 与JSON.parse()

关于这两个方法:具体解析方法如下

1. JSON.stringify()是将JSON类数据转换成JSON字符串

语法:JSON.stringify(value,replacer?,space?)

备注:value==》必选,例如对象,类,数组

     replacer?可选,第一个数组,第二个是方法(函数)

   sapce?可选,分隔(默认值是单行输出,输出没有空格)第一种类型数字:小于0解析成0,大于10解析为10.

 实例:1.参数/value

  var jsonValue = new Object();

jsonValue.name = 'JavaScript-deepUnderstand';

jsonValue.page = 334;

jsonValue.level = 'easy'

console.log(JSON.stringify(jsonValue));//{"name":"JavaScript-deepUnderstand","page":334,"level":"easy"}

 

2.replacer?/方法(函数):此方法会在值转化成字符串的之前转换成树节点的值

  

  function repalcer(key,value){

if(typeof value === 'number'){

value = value * 2;

}

return value;

}

repalcer();

 

console.log(JSON.stringify({a: 5, b: [2,8]} ,repalcer));//{"a":10,"b":[4,16]}

 

 

2-1replacer?数组:如果第一个参数是数组,第二个也是数组,则只显示第一个数组。

 

 

var animal = new Array();
animal[0] = 'monkey';
animal[1] = 'elephant';
animal[2] = 'lion';
var plant = new Array();
plant[0] = 'bamboo';
plant[1] = 'tree';
plant[2] = 'grass';
console.log(JSON.stringify(animal,plant));//["monkey","elephant","lion"]

 

3. space? 分隔符 第一:数字大于10解析成10 小于0解析成0 。第二:使用给定的字符为每层缩进。只有前10个字符会被用到。

 

 

console.log(JSON.stringify({a:0,b: ['
']},null,9));

 

输入如下:

{
         "a": 0,
         "b": [
                  "
"
         ]
}

 

3-1space? 分隔符 第二:使用给定的字符为每个层级缩进,只有前10个字符会被用到

 

 

console.log(JSON.stringify({a:0,b:['
']},null,'--'));

 

{
--"a": 0,
--"b": [
----"
"
--]

JSON.parse() 两个参数:第一个是value 第二个reviver?节点访问函数,它用来来转换解析后的数据。

 

语法: JSON.parse(value,reviver?)

 

实例:JSON.parse(value)

 

 

 console.log(JSON.parse('"string"'))//string

 

console.log(JSON.parse('4567890'));//4567890
console.log(JSON.parse('[1,2,3]'));//[1,2,3]

实例:JSON.parse(value,reviver?)

function dateReviver (key,value){
    if(typeof value === 'string'){
        var x = Date.parse(value);
         if(!isNaN(x)){
             return new Date(x);
         }
     }
             return value;
}
var str = '{"type": "javaScript", "page": "338" ,"date" : "2010-07-22T22:00:00.000z" }';
console.log(JSON.parse(str,dateReviver));
//Object {type: "javaScript", page: Sat Jan 01  338 00:00:00 GMT+0800 (CST), date: Fri Jul 23 2010 06:00:00 GMT+0800 (CST)}

 

 

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/majidaozi/p/6510541.html