標籤:return 深度 最大值 code 自訂函數 size ons key 自訂
按照 JSON 的規範,使用 JSON.stringify() 做對象序列化時,如果一個屬性為函數,那這個屬性就會被忽略。
const data1 = { a: ‘aaa‘, fn: function() { return true }}JSON.stringify(data)// 結果是 "{"a":"aaa"}"
還有一種情況,一個屬性的值為 undefined
const data2 = { a: ‘abc‘, b: undefined}JSON.stringify(data2)// 結果是 "{"a":"abc"}"
如果屬性為 null
則可以正常序列化這個屬性:
const data3 = { a: ‘abc‘, b: null}JSON.stringify(data3)// 結果是 "{"a":"abc","b":null}"
因為 null
可表示已經賦值,而 undefined
表示未定義、未賦值,所以執行 JSON.stringify
不會處理。
stringify
函數
stringify
函數的定義為 JSON.stringify(value [, replacer [, space]])
後面還帶有我不常用兩個選擇性參數 replacer 和 space
value
參數不多解釋,replacer
其實就是一個自訂函數,可以改變 JSON.stringify
的行為,space
就是格式化輸出,最大值為 10,非整數時取值為 1
stringify
輸出
Function
本質上無論怎麼改,stringify
還是不會輸出 Function
,但是 Function
可以調用 toString()
方法的,所以思路就很明了了。
const data1 = { a: ‘aaa‘, fn: function() { return true }}const replace = function(k ,v) { if(typeof v === ‘function‘) { return Function.prototype.toString.call(v) } return v}JSON.stringify(data1, replace)// 結果 "{"a":"aaa","fn":"function () {\n return true\n }"}"
同理可證 undefined
也能輸出了
const replace = function(k ,v) { if(v === undefined){ return ‘undefined‘ } return v}
stringify
格式化輸出
JSON.stringify
的第三個參數很簡單,相當於我們編輯器的 tab_size
const data4 = { a: ‘abc‘, b: null, c: { x: ‘xxx‘, y: ‘yyy‘, z: 2046 }, d: 9527}JSON.stringify(data4, null, 2);// 輸出結果/*"{ "a": "abc", "b": null, "c": { "x": "xxx", "y": "yyy", "z": 2046 }, "d": 9527}"*/
toJSON
方法
toJSON
是個覆蓋函數,盡量少用,看了代碼就懂了:
const data5 = { a: ‘abc‘, b: null, c: { x: ‘xxx‘, y: ‘yyy‘, z: 2046 }, d: 9527, toJSON: function() { return ‘WTF‘ }}JSON.stringify(data5, null, 2);// 結果返回 "WTF"
深度使用JSON.stringify()