“JSON.stringify"中的“符号键控"是什么意思

2022-01-19 00:00:00 javascript sequelize.js stringify

有一个Node.js生成的Object,当我使用console.log时是这样的:

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

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

当我使用 JSON.stringify 时,它会返回这个字符串:

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

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

我检查了 mozilla 开发者中心,发现 这个:

I checked the mozilla developer center and found this:

所有 symbol-keyed 属性将被完全忽略,即使在使用替换功能时也是如此.

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

我认为 'dataValues' 必须是 'symbol-keyed' 属性,但 'symbol-keyed' 是什么意思?

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

顺便说一句,我使用 sequelizejs ORM 库来生成这个对象.

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

推荐答案

我终于在同一个地方找到了原因页面:

I found the reason finally in the same page:

如果被字符串化的对象有一个名为 toJSON 且值为函数的属性,则 toJSON 方法自定义 JSON 字符串化行为:而不是被序列化的对象,调用时由 toJSON 方法返回的值将被序列化.

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.

它在浏览器上正常运行.这是 jsfiddle 按照我的要求运行它.

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

代码:

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}

相关文章