我正在使用 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"}
[ pen ]
请问这是为什么?我搜索了 MDN page , json2解析器文档。 我无法在任何地方找到这种行为的记录。
我怀疑这是使用 for...in
循环的结果 only go through [[enumerable]]属性(至少在 json2
的情况下)。这可能可以通过返回可枚举和不可枚举属性的 Object.getOwnPropertyNames
之类的东西来完成。
不过,这可能会对序列化产生问题(由于反序列化)。
tl;dr
- 为什么
JSON.stringify
只序列化可枚举属性? - 是否在任何地方记录了此行为?
- 我如何自己实现序列化不可枚举的属性?
最佳答案
它在 ES5 spec 中指定.
If Type(value) is Object, and IsCallable(value) is 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 .这是相关部分:
Let K be an internal List of Strings consisting of the names of all the own properties of value whose [[Enumerable]] attribute is true. The ordering of the Strings should be the same as that used by the Object.keys standard built-in function.
关于javascript - 为什么 JSON.stringify 不序列化不可枚举的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733878/