Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

javascript - Why does JSON.stringify not serialize non-enumerable properties?

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"}

[pen]

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.

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

  • Why does JSON.stringify only serialize enumerable properties?
  • Is this behavior documented anywhere?
  • How can I implement serializing non-enumerable properties myself?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's specified in the 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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...