Why is JSON.stringify not serializing prototype values?

Simply because this is the way JSON works. From the ES5 spec:

Let K be an internal List of Strings consisting of the names of all the own properties of value whose [[Enumerable]] attribute is true.

This makes sense, because there is no mechanism in the JSON specification for preserving information that would be required to parse a JSON string back into a JavaScript object if inherited properties were included. In your example, how would this parsed:

{ “initialisedValue” : “You can see me!”, “uninitialisedValue” : “You can’t see me!” }

There is no information to parse it into anything other than a flat object with 2 key-value pairs.

And if you think about it, JSON is not intended to map directly to JavaScript objects. Other languages must be able to parse JSON strings into simple structures of name-value pairs. If JSON strings contained all the information necessary to serialize complete JavaScript scope chains, other languages may be less capable of parsing that into something useful. In the words of Douglas Crockford on json.org:

These [hash tables and arrays] are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

Leave a Comment