小编典典

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

json

我正在使用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解析器文档。我找不到任何地方记录此行为。

我怀疑这是使用仅通过[[enumerable]]属性的for... in循环(至少在情况下)的结果。可以使用类似的方法同时返回可枚举和不可枚举的属性。不过,这可能会导致序列化(由于反序列化)。json2``Object.getOwnPropertyNames

tl; dr

  • 为什么JSON.stringify只序列化可枚举的属性?
  • 此行为记录在任何地方吗?
  • 我如何自己实现序列化不可枚举的属性?

阅读 317

收藏
2020-07-27

共1个答案

小编典典

它在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的value所有自身属性
的名称组成。字符串的顺序应与Object.keys标准内置函数所使用的顺序相同。

2020-07-27