Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON相关知识 #2

Open
xiongchengbin opened this issue May 5, 2018 · 1 comment
Open

JSON相关知识 #2

xiongchengbin opened this issue May 5, 2018 · 1 comment

Comments

@xiongchengbin
Copy link
Owner

  1. json序列化和解析实现: 里面包含三种JSON数据解析方式:eval、递归方式、状态机方式
  2. JSON stringify函数介绍: 支持三个参数value、replacer、space,replacer支持函数或者数组,如果是函数的话,返回undefined表示忽略元素;space支持数字或者字符串,最大长度为10。如果value有toJSON方法,会序列化toJSON的返回结果.
  3. JSON parse函数介绍: 支持两个参数value、reviver,reviver 函数可以对解析的值进行转换。
@xiongchengbin
Copy link
Owner Author

xiongchengbin commented May 5, 2018

JSON.stringify示例

const obj = {title: 'hello', authors: ['a', 'b', 'c', 'd', function() {}], year: 2011};
JSON.stringify(book); // => {"title":"hello","authors":["a","b","c","d", null],"year":2011}
JSON.stringify(book, ['title', 'year']); // => {"title":"hello","year":2011}
JSON.stringify(book, function (key, value) {
    console.log(`key & value: ${key} -> `, value);
    if (key === 'title') {
        return undefined;
    }
    if (key === 'authors') {
        return [...value, 2]
    }
    return value;
})
// 输出的结果为:
/*
key & value: title ->  hello
key & value: authors ->  [ 'a', 'b', 'c', 'd', [Function] ]
key & value: 0 ->  a
key & value: 1 ->  b
key & value: 2 ->  c
key & value: 3 ->  d
key & value: 4 ->  function () {}
key & value: 5 ->  2
key & value: year ->  2011
{"authors":["a","b","c","d",null,2],"year":2011}
*/

如果针对数组返回undefined的,不会删除元素,只会替换为null,函数序列化后也是返回null。

JSON.parse示例

JSON.parse('{"p": 5}', function (k, v) {
    if(k === '') return v;     // 如果到了最顶层,则直接返回属性值,
    return v * 2;              // 否则将属性值变为原来的 2 倍。
});                            // { p: 10 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant