原文: The 80/20 Guide to JSON.stringify in JavaScriptjavascript
不少库都有用 JSON.stringify()
,现代浏览器也基本支持这个接口,甚至 IE8 就已经支持了。html
JSON.stringify()
的做用是把一个 JS 对象转为 JSON,能够搭配 JSON.parse()
做为深拷贝的一种实现方式使用。java
// 循环对象
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
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
是一个回调函数,参数为 key/value
返回值做为 JSON
的值。ide
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}}'
复制代码
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
ui
NaN
, Infinity
一概转为 null
function
, undefined
一概转为忽略掉