javascript - 为什么 JSON.stringify 不序列化不可枚举的属性?

标签 javascript json serialization

我正在使用 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/

相关文章:

javascript - Phonegap/Cordova - 代码不在 android 上播放音频(不是路径问题)

javascript - 为什么返回值要与 JavaScript 中的 return 语句在同一行?

java - 将 JSONObject 中的所有键放入 String 数组

c# - Json.NET - 值类型成员没有反序列化?

php - 将带有图像路径的数组序列化到数据库中

javascript - 如何使用 RegEx 排除以零开头的字母字符和数字?

javascript - jQuery 如何完成命令链?

javascript - 使用 transformRequest 将 JSON 转换为 FormURL 编码数据

python - 将 jsonschema 转换为 Django REST 序列化器的工具?

java - 通过序列化/GSON 将对象自动转换为 double