为什么 JSON.stringify 不序列化不可枚举的属性? [英] Why does JSON.stringify not serialize non-enumerable properties?

查看:40
本文介绍了为什么 JSON.stringify 不序列化不可枚举的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JavaScript 将对象序列化为 JSON 字符串,

I'm serializing objects to JSON strings with JavaScript,

我注意到只有可枚举的对象属性被序列化:

I noticed only enumerable object properties get serialized:

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 解析器文档.我在任何地方都找不到这种行为的记录.

I'm wondering why that is? I've searched through the MDN page, the json2 parser documentation. I could not find this behavior documented any-where.

我怀疑这是使用 for... in 循环的结果 只通过 [[enumerable]] 属性(至少在 json2 的情况下).这可能可以通过类似 Object.getOwnPropertyNames 的东西来完成,它返回可枚举和不可枚举的属性.不过,序列化可能会有问题(由于反序列化).

I suspect this is the result of using for... in loops that only go through [[enumerable]] properties (at least in the case of json2). This can probably be done with something like Object.getOwnPropertyNames that returns both enumerable, and non-enumerable properties. That might be problematic to serialize though (due to deserialization).

tl;dr

  • 为什么 JSON.stringify 只序列化可枚举的属性?
  • 这种行为是否有任何记录?
  • 如何自己实现不可枚举属性的序列化?
  • Why does JSON.stringify only serialize enumerable properties?
  • Is this behavior documented anywhere?
  • How can I implement serializing non-enumerable properties myself?

推荐答案

它在 ES5 规范中指定.

如果 Type(value) 是 Object,并且 IsCallable(value) 是 false

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.这是相关部分:

So, let's look at JO. Here's the relevant section:

让 K 是一个内部字符串列表,由所有 [[Enumerable]] 属性为 true 的 value 自身属性的名称组成.字符串的顺序应与 Object.keys 标准内置函数使用的顺序相同.

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.

这篇关于为什么 JSON.stringify 不序列化不可枚举的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆