有一个 Node.js 生成的对象,当我使用 console.log
时它看起来像这样:
{ dataValues: { a: 1, b: 2 }, fn1: function(){}, fn2: function(){} }
当我使用 JSON.stringify
时,它返回这个字符串:
{"a":1,"b":1}
我查看了 mozilla 开发者中心并找到了 this :
All symbol-keyed properties will be completely ignored, even when using the replacer function.
我认为“dataValues”必须是“symbol-keyed”属性,但“symbol-keyed”是什么意思?
顺便说一句,我使用 sequelizejs ORM 库来生成这个对象。
最佳答案
我终于在同一个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.
它在浏览器上正常运行。 这是 jsfiddle按照我的要求运行它。
代码:
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}
关于javascript - 'symbol-keyed'中的 `JSON.stringify`是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25217064/