JSON.stringify() 語法
JSON.stringify(value[, replacer[, space]])數組
value 被序列化爲字符串的對象函數
replacer 根據類型不一樣,其行爲也不同。若是是一個函數類型,則至關因而一個filter,能夠對序列化的鍵值對進行加工處理;若是是一個數組,則只有符合數組中名稱的key纔會被輸出spa
space 若是爲0或不填,則不進行格式化處理;若是爲大於0的數值,則表示每級縮進空格數;若是是一個字符串,則表示每級縮進時替代空格進行填充的字符串內容。code
經過如下的data做爲示例:對象
let data = { name: 'wang', age: 28, address: null, favorites: undefined, company: { name: 'world village', address: 'Beijing city' } }
不加任何參數,直接輸出:ci
console.log(JSON.stringify(data))
結果爲:字符串
{"name":"wang","age":28,"address":null,"company":{"name":"world village","address":"Beijing city"}}
第二個參數爲數組:string
console.log(JSON.stringify(data, ['name', 'age']))
結果爲:it
{"name":"wang","age":28}
第二個參數是一個函數:console
console.log( JSON.stringify(data, (k, v) => { if ('age' == k) { return undefined } return v }) )
結果爲:
{"name":"wang","address":null,"company":{"name":"world village","address":"Beijing city"}}
若是第三個參數爲0或者null:
console.log(JSON.stringify(data, null, 0))
則結果爲:
{"name":"wang","age":28,"address":null,"company":{"name":"world village","address":"Beijing city"}}
若是第三個參數爲大於0的數值:
console.log(JSON.stringify(data, null, 2))
則結果爲:
{ "name": "wang", "age": 28, "address": null, "company": { "name": "world village", "address": "Beijing city" } }
若是第三個參數爲字符串:
console.log(JSON.stringify(data, null, '**'))
則結果爲:
{ **"name": "wang", **"age": 28, **"address": null, **"company": { ****"name": "world village", ****"address": "Beijing city" **} }
若是過濾值爲null或者undefined的鍵值對?
let data = { name: 'wang', age: 28, address: null, favorites: undefined, men: true, women: false, company: { name: 'world village', address: 'Beijing city' } } console.log( JSON.stringify(data, (k, v) => { if (null != v && undefined != v) return v }) )