JSON.stringify() && JSON.parse()

154 阅读2分钟

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

  • 必须: value 要序列化的值

  • 可选: replacer [ function | array] 在序列化过程中对返回的内容做处理

  • 可选: space [ number | string ] 空格数

// 举例对象
var foo = {
  model: 'box',
  week: 45,
  month: 7,
}

replacer

  • 传入的 replacer 是一个函数
    • replacer 函数中第一轮遍历抛出的参数 key 和 value 将会是 '' 和 foo 自身
    • 返回 null,是修改 当前 key 的值,返回 undefined,是 不返回 当前的 key
const replacer = (key, value) => {
  console.log('%c key', 'color: #eea24b', key)
  console.log('%c value', 'color: #eea24b', value)
  if (typeof value === 'string') {
    // return undefined
    return null
  }
  if (value == 7) {
    return '修改过后的 box'
  }
  return value
}
const res = JSON.stringify(foo, replacer, 6)
console.log('%c 序列化结果', 'color: #eea24b', res)

输出结果

image.png

  • 如果传入的 replacer 是一个 array(由序列化对象 foo 中的 key 组成)
    • 只有数组中包含的属性才会被序列化到最终的 JSON 字符串中
const targetObj = JSON.stringify(foo, ['model', 'week'], 4)
console.log('%c 序列化结果','color: #eea24b', targetObj);

// expect output: 
// 序列化结果: {
//    "model": "box",
//    "week": 45
// }

space

  • 指定缩进用的空白字符串,用于美化输出(pretty-print);
  • 如果参数是个数字,它代表有多少的空格;上限为 10。该值若小于 1,则意味着没有空格;
  • 如果该参数为字符串(当字符串长度超过 10 个字母,取其前 10 个字母),该字符串将被作为空格;
  • 如果该参数没有提供(或者为 null),将没有空格。

JSON.parse()

  • 必选:要解析的值
  • 可选:转换器,如果传入该参数 (函数),可以用来修改解析生成的原始值,调用时机在 parse 函数返回之前。

当遍历到最顶层的值(解析值)时,传入 reviver 函数的参数会是空字符串 ""(因为此时已经没有真正的属性)和当前的解析值(有可能已经被修改过了),当前的 this 值会是 {"": 修改过的解析值},在编写 reviver 函数时,要注意到这个特例。(这个函数的遍历顺序依照:从最内层开始,按照层级顺序,依次向外遍历)

JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}', function (k, v) {
  // 输出当前的属性名,从而得知遍历顺序是从内向外的
  console.log('key && value', k, v);
  // 最后一个属性名会是个空字符串。
  return v; // 返回原始属性值,相当于没有传递 reviver 参数
});

输出结果: image.png

JSON.parse() 不允许用逗号作为结尾

// both will throw a SyntaxError
JSON.parse("[1, 2, 3, 4, ]");
JSON.parse('{"foo" : 1, }');