JSON序列化对象-mdn

描述

  • JSON是一种语法
  • 用来序列化对象,数组,字符串,布尔值和null。其他都不可以

一、JSON.parse(text,[reviver])  

  • 描述:
    • 解析JSON字符串;返回值:Object对象(对象/数组...)
  • 参数
    • text:JSON字符串

    • reviver:转换器,一个遍历的函数,对返回的JS对象进行处理

二、JSON.stringify(value,[replacer,[space]])

  • 参数
    • replacer 函数/数组
      • // replacer为函数
        var replacer = function (key,value){
            if(typeof value === "string"){return undefined};
            return value;
        }
        var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
        JSON.stringify(foo,replacer); // {"week": 45,"month": 7}
        
        
        //replacer为数组
        JSON.stringify(foo,['model','week']); //{"model": "box","week": 45}
    • space 控制结果字符串里的间距
      • JSON.stringify({a:"a"},null," ") // space为字符串
        JSON.stringify({a:"a",null,10}) //space为数组(最多为10)
        JSON.stringify({ uno: 1, dos : 2 }, null, '\t')  //space为制表符
        // '{            \ 
        //     "uno": 1, \
        //     "dos": 2  \
        // }' 
  • 描述
    • 布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值。
    • undefined、任意的函数以及 symbol 值,在序列化过程中会被忽略(出现在非数组对象的属性值中时)或者被转换成 null(出现在数组中时)。函数、undefined 被单独转换时,会返回 undefined,如JSON.stringify(function(){}) or JSON.stringify(undefined).
      • 所以使用序列化进行深拷贝对象或者数组,如果值为函数则会被忽略,序列化深拷贝的缺点
    • NaN 和 Infinity 格式的数值及 null 都会被当做 null。

猜你喜欢

转载自blog.csdn.net/weixin_43374360/article/details/108661203