能處理的(安全JSON):
通常爲對象或者數組,也可以是字符串、數字、布爾值和null,結果都是字符串('aa','33','null','true')
不能處理的(不安全JSON):
undefined
,function
,symbol
,循環引用的對象(自己裏面引用了自己)
擴展知識:JSON.stringify在轉換之前,如果傳入對象中的有.toJSON()
方法,會先調用toJSON()
,用它的返回值再進行字符串化,另可以自行編寫toJSON()
方法
參數:
JSON.stringify(json [, replacer] [, space])
除了常用的,只傳一個參數,還有另外兩個參數replacer
和space
可供選擇:
1、replacer
可以傳遞:
①函數,此函數有兩個參數,傳入json的key
和value
大家可以打印一下key,和value,看得出對於json是由內而外遞歸遍歷出來的,把嵌套json直接扁平化了,所以我們可以省去還得遍歷多層級json的複雜情況,直接在JSON.stringify()
裏面操作即可
function replacer(key, value) {
console.log(key,value) //見下key和value註釋
if (typeof value === "string") {
return undefined;
}
return value;
}
var foo = {factoryLocation:'shanghai', info: {brand:'tesla',Mileage :{modelY:660,modelX:550}}, month: 9};
var jsonString = JSON.stringify(foo, replacer); // 輸出爲:"{"info":{"Mileage":{"modelY":660,"modelX":550}},"month":9}"
// key和value:
// {factoryLocation: "shanghai", info: {…}, month: 9}
// factoryLocation shanghai
// info : {brand: "tesla", Mileage: {…}}
// brand tesla
// Mileage : {modelY: 660, modelX: 550}
// modelY 660
// modelX 550
// month 9
②數組:由一個或多個字符串構成的數組,代表指定需要被轉換的鍵值對,其他未指定則忽略:
JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', 只保留“week”和“month”屬性值。
2、最後一個可選參數space,可以傳入製表符等符號代表字符串化後的縮進形式,也可傳入數字代表縮進空格數量:
JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}'
//使用製表符(\t)來縮進:
JSON.stringify({ uno: 1, dos : 2 }, null, '\t')
// '{ \
// "uno": 1, \
// "dos": 2 \
// }'