JSON 对象蕴含两个办法:一是用于解析成 JSON 对象的 parse();二是用于将对象转换为 JSON 字符串办法的 stringify()。这两个办法比拟罕用

JSON.parse

该办法的语法为:JSON.parse(text[, reviver])
参数阐明:

text:必须, 一个无效的 JSON 字符串。
reviver: 可选,一个转换后果的函数, 将为对象的每个成员调用此函数。

第二个参数应用例子,第二个参数能够将待处理的字符串进行肯定的操作解决

 let result = JSON.parse('{"a":3}', (k, v) => {     if (k === "")         return v     return v * 2 }) console.log(result)  // {a:6}

JSON.stringify

MDN形容
avaScript 对象或值转换为 JSON 字符串,默认该办法有三个参数

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

value:必须, 要转换的 JavaScript 值(通常为对象或数组)。

replacer:可选。用于转换后果的函数或数组。如果 replacer 为函数,则 JSON.stringify 将调用该函数,并传入每个成员的键和值。应用返回值而不是原始值。如果此函数返回 undefined,则排除成员。根对象的键是一个空字符串:""。如果 replacer 是一个数组,则仅转换该数组中具备键值的成员。成员的转换程序与键在数组中的程序一样。

space:可选,文本增加缩进、空格和换行符,如果 space 是一个数字,则返回值文本在每个级别缩进指定数目的空格,如果 space 大于 10,则文本缩进 10 个空格。space 也能够应用非数字,如:\t。

应用例子

JSON.stringify({ x: [1, undefined, function(){}, Symbol('')] }) // {"x":[1,null,null,null]}function replacer(key,value){    if(typeof value === "string"){        return undefined    }    return value}var foo = {a:"aa",b:"bb",c:1,d:"d",e:5}// 通过替换办法把对象中的属性为字符串的过滤掉var jsonstr1= JSON.stringify(foo,replacer)console.log(jsonstr1) // {"c":1,"e":5}// 第三个参数传入的是多个空格的时候,则会减少后果字符串外面的间距数量console.log(JSON.stringify({a:1},null," "))// {//   "a": 1// }console.log(JSON.stringify({a:1},null,"")) // {"a":1}

JSON.stringify办法的实现要思考到各种数据类型输入的理论状况。

输出输入
undefined"undefined"
boolean"true/false"
number字符串类型数字
symbolundefined
null"null"
stringstring
NaN Infinity"null"
functionundefined
Array数组中呈现 undefined,function,symbol"null"
RegExp"{}"
DateDate的toJson()字符串,对蕴含循环援用的对象(对象之间互相援用,造成有限循环)执行此办法,会抛出谬误。
一般的Object如果有toJson()办法,序列化toJson()返回值;如果属性中呈现undefinde,函数,symbol,疏忽;所有以Symbol为属性键的属性都会被疏忽,即使 replacer 参数中强制指定蕴含了它们。

此外, 其余类型的对象,包含 Map/Set/WeakMap/WeakSet,仅会序列化可枚举的属性

实现代码

function myJsonStringfy(e) {    let type = typeof e;    // typeof []  'object'    // typeof {}  'object'    if (type !== "object") {        let result = e;        // 根底数据类型解决        if (Number.isNaN(e) || e === Infinity || e === -Infinity) {            //NaN 和 Infinity 序列化返回 "null"            result = "null"        } else if (type === "function" || type === "undefined" || type === "symbol") {            // 因为 function 序列化返回 undefined,因而和 undefined、symbol 一起解决            return undefined        } else if (type === "string") {            return `"${e}"`        }        return String(result)    } else if (type === "object") {        // 解决typeof null 后果是object历史遗留BUG        console.log(e, e.toJSON)        if (e === null) {            return "null"        } else if (e.toJSON && typeof e.toJSON === "function") {            return myJsonStringfy(e.toJSON())        } else if (e instanceof Array) {            //解决数组            let result = []            e.forEach((item, index) => {                //   Array数组中呈现 undefined,function,symbol 返回字符串null                if (typeof item === "undefined" || typeof item === "function" || typeof item === "symbol") {                    result[index] = "null";                } else {                    result[index] = myJsonStringfy(item)                }            })            result = `[${result}]`            return result.replace(/'/g, '"');        } else {            // 一般对象状况            let result = []            Object.keys(e).forEach(item => {                console.log("...", item, typeof item)                if (typeof item !== "symbol") {                    // key 如果是 symbol 对象,疏忽                    if (e[item] !== undefined && typeof e[item] !== 'function' && typeof e[item] !== 'symbol') {                        //键值如果是 undefined、function、symbol 为属性值,疏忽                        result.push('"' + item + '"' + ":" + myJsonStringfy(e[item]));                    }                }            })            return ("{" + result + "}").replace(/'/g, '"');        }    }}