深度使用JSON.stringify()

來源:互聯網
上載者:User

標籤: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()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.