Why is JSON.stringify not serializing prototype values?

前端 未结 3 523
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 12:15

I have been working with a fair bit of JSON parsing and passing in Javascript within Node.js and browsers recently and bumped into this conundrum.

Any objects I crea

3条回答
  •  一个人的身影
    2020-11-29 12:35

    I'd like to add that, even though JSON.stringify will only stringify the object's own properties, as explained in the accepted answer, you can alter the behavior of the stringification process by specifying an array of String as the second parameter of JSON.stringify (called a replacer array).

    If you specify an array of String with the whitelist of properties to stringify, the stringification algorithm will change its behavior and it will consider properties in the prototype chain.

    From ES5 spec:

    1. If PropertyList is not undefined, then

      a. Let K be PropertyList.

    2. Else

      a. 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.

    If you know the name of the properties of the object to stringify beforehand, you can do something like this:

    var a_string = JSON.stringify(a, ["initialisedValue", "uninitialisedValue"]);
    //  a_string == { "initialisedValue" : "You can see me!", "uninitialisedValue" : "You can't see me!" }
    

提交回复
热议问题