JSON.stringify

原文: The 80/20 Guide to JSON.stringify in JavaScript

很多库都有用 JSON.stringify(),现代浏览器也基本支持这个接口,甚至 IE8 就已经支持了。

JSON.stringify() 的作用是把一个 JS 对象转为 JSON,可以搭配 JSON.parse() 作为深拷贝的一种实现方式使用。

会遇到的一些问题:

  • 出现循环对象 => 报类型错误
  • 不能正确转换,或者忽略某些值
// 循环对象
const obj = {};
// Cyclical object that references itself
obj.prop = obj;
// Throws "TypeError: TypeError: Converting circular structure to JSON"
JSON.stringify(obj);

// NaN, Infinity => null 
const obj = { nan: parseInt('not a number'), inf: Number.POSITIVE_INFINITY };
JSON.stringify(obj); // '{"nan":null,"inf":null}'

// 忽略函数和 undefined
const obj = { fn: function() {}, undef: undefined };
// Empty object. `JSON.stringify()` removes functions and `undefined`.
JSON.stringify(obj); // '{}'
复制代码

循环对象是 JSON.stringify() 抛出异常的唯一情况,即使这样我们也需要使用 try/catch 去捕获异常。

美化输出格式

JSON.stringify() 接收三个参数,第三个参数则是 space,当为数字时代表缩进几个空格,当为字符串时,代表填充了字符串。

const obj = { a: 1, b: 2, c: 3, d: { e: 4 } };
JSON.stringify(obj); 
// '{"a":1,"b":2,"c":3,"d":{"e":4}}'

JSON.stringify(obj, null, '  ');
// Use 2 spaces when formatting JSON output. Equivalent to the above.
JSON.stringify(obj, null, 2);
// {
//   "a": 1,
//   "b": 2,
//   "c": 3,
//   "d": {
//     "e": 4
//   }
// }

JSON.stringify(obj, null, '__');
// {
// __"a": 1,
// __"b": 2,
// __"c": 3,
// __"d": {
// ____"e": 4
// __}
// }
复制代码

自定义 replacer

replacer 是一个回调函数,参数为 key/value 返回值作为 JSON 的值。

const obj = { a: 1, b: 2, c: 3, d: { e: 4 } };

JSON.stringify(obj, function replacer(key, value) {
  if (typeof value === 'number') {
    return value + 1;
  }
  return value;
});
// `replacer` increments every number value by 1. The output will be:
// '{"a":2,"b":3,"c":4,"d":{"e":5}}'
复制代码

toJSON() 函数

JSON.stringify() 会遍历对象属性是否有 toJSON() 有的话直接用该返回值, toJSON() 可以返回任何值,当返回值为 undefined 时则会被忽略掉。

const obj = {
  name: 'Jean-Luc Picard',
  nested: {
    test: 'not in output',
    toJSON: () => 'test'
  }
};

// '{"name":"Jean-Luc Picard","nested":"test"}'
JSON.stringify(obj);
复制代码

即使是使用了 replacer, toJSON

  • 只要返回值为 NaN, Infinity 一律转为 null
  • 只要返回值为 function, undefined 一律转为忽略掉

猜你喜欢

转载自blog.csdn.net/weixin_33724659/article/details/91368634