What does 'symbol-keyed' mean in 'JSON

2019-08-15 08:05发布

问题:

There is a Object generated by NodeJS, it looks like this when I use console.log:

{ dataValues: { a: 1, b: 2 }, fn1: function(){}, fn2: function(){} }

when I use JSON.stringify, it return this string:

{"a":1,"b":1}

I checked the mozilla developer center and found this:

All symbol-keyed properties will be completely ignored, even when using the replacer function.

I think the 'dataValues' must be the 'symbol-keyed' property, but what does 'symbol-keyed' mean?

btw, I use the sequelizejs ORM lib to generate this object.

回答1:

I found the reason finally in the same page:

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized.

It runs on browser normally. Here is the jsfiddle to run it like I asked.

Code:

function test(data) {
    for(var key in data){
        this[key] = data[key];
    }
}

test.prototype.toJSON = function(){
    return this.dataValues;
}

var a = new test({dataValues: {a:1, b:2}});

console.log(a);//the instance
console.log(JSON.stringify(a));//{"a":1,"b":1}


回答2:

Nah, the relevant part to your issue is this blurb:

If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).

So in other words, if your JSON object contains functions, they are omitted during the JSON.stringify process.

"symbol-keyed" refers to a new primitive type introduced in ecmascript6. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof for more info.

This is an example of a "symbol-keyed" property:

{[Symbol("foo")]: "foo"}

Reference for JavaScript Symbol: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol