JSON.stringify(value[, replacer[, space]])
JSON.stringify()
的第一個參數是可序列化的js對象
replacer
第二個參數是一個replacer,replacer可以是一個函數或者一個字符串數組
當replacer是數組時,相當于一個白名單,只有在這個數組中的屬性最終會被序列化
JSON.stringify({
name: 'acky',
age: 18,
gender: 'male'
}, ['name', 'age'])
// result
// "{"name":"acky","age":18}"
當replacer是函數時,接受兩個參數,key和value,注意:
Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified
一開始會先接收到key為空,value為要序列化的對象,必須返回這個對象,否則JSON.stringify()
沒有結果,因為會遞歸對這個對象上的key:value調用replacer函數
image.png
var rep = (key, value) => {
if (key === 'name') {
return value.toUpperCase()
}
if (key === 'age') {
return ++value
}
if (key === 'gender') {
return 'female'
}
return value
}
JSON.stringify({
name: 'acky',
age: 18,
gender: 'male'
}, rep)
// result
// "{"name":"ACKY","age":19,"gender":"female"}"
space
第三個參數表示的是每個字符前的縮進,可以是字符串,或者數字,數字表示的是縮進的空格,最大為10
當使用字符串作為縮進的時候
JSON.stringify({ name: 'acky', age: 19, gender: 'male' }, null, 'hello world')
// result
"{
hello worl"name": "acky",
hello worl"age": 19,
hello worl"gender": "male"
}"
當使用數字表示縮進的空格時
JSON.stringify({ name: 'acky', age: 19, gender: 'male' }, null, 10)
// result
"{
"name": "acky",
"age": 19,
"gender": "male"
}"