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

查看:286
本文介绍了为什么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 <的结果/ code> 仅通过[[可枚举]] 属性的循环(至少在 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 。字符串的顺序应与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天全站免登陆