簡體   English   中英

為什么JSON.stringify沒有序列化不可枚舉的屬性?

[英]Why does JSON.stringify not serialize non-enumerable properties?

我正在使用JavaScript將對象序列化為JSON字符串,

我注意到只有可枚舉的對象屬性被序列化:

var a = Object.create(null,{
  x: { writable:true, configurable:true, value: "hello",enumerable:false },
  y: { writable:true, configurable:true, value: "hello",enumerable:true }
});
document.write(JSON.stringify(a)); //result is {"y":"hello"}

[ ]

我想知道為什么會這樣? 我搜索了MDN頁面json2解析器文檔。 我無法在任何地方找到這種行為。

我懷疑這是使用for... in循環只能通過[[enumerable]]屬性的結果(至少在json2的情況下)。 這可以通過像Object.getOwnPropertyNames這樣的東西來完成,它返回可枚舉和不可枚舉的屬性。 這可能是序列化的問題(由於反序列化)。

TL;博士

  • 為什么JSON.stringify只序列化可枚舉屬性?
  • 這種行為記錄在哪里嗎?
  • 如何自己實現序列化非可枚舉屬性?

它在ES5規范中指定。

如果Type(value)是Object,則IsCallable(value)為false

If the [[Class]] internal property of value is "Array" then

    Return the result of calling the abstract operation JA with argument value.

Else, return the result of calling the abstract operation JO with argument value.

那么,讓我們來看看JO 這是相關部分:

設K是一個內部字符串列表,由[[Enumerable]]屬性為true所有值屬性的名稱組成。 字符串的順序應與Object.keys標准內置函數使用的順序相同。

正如@ThiefMaster上面回答的那樣,它在規范中指定

但是,如果你知道你想要提前序列化的非可枚舉屬性的名稱,你可以通過將一個替換器函數作為第二個參數傳遞給JSON.stringify()( MDN上的文檔 )來實現它,就像這樣

 var o = { prop: 'propval', } Object.defineProperty(o, 'propHidden', { value: 'propHiddenVal', enumerable: false, writable: true, configurable: true }); var s = JSON.stringify(o, (key, val) => { if (!key) { // Initially, the replacer function is called with an empty string as key representing the object being stringified. It is then called for each property on the object or array being stringified. if (typeof val === 'object' && val.hasOwnProperty('propHidden')) { Object.defineProperty(val, 'propHidden', { value: val.propHidden, enumerable: true, writable: true, configurable: true }); } } return val; }); console.log(s); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM