原文: 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
一概轉爲忽略掉