javascript - 'symbol-keyed'中的 `JSON.stringify`是什么意思

标签 javascript stringify sequelize.js

有一个 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/

相关文章:

javascript - Angular 在 ng-model 中使用 $index

javascript - 嵌套对象上的 JSON.stringify 忽略嵌套对象

javascript - JSON.stringify 中未捕获的 InvalidStateError

javascript - 通过其他模型加入

mysql - 使用日期序列化查询

javascript - 根据数字 Id 对 li 标签进行排序

c# - javascript中设置的标签文本未在服务器端显示标签文本

javascript - 提取所有使用过的 JavaScript 变量

ruby-on-rails - 使用 Factory Girl 时未定义的方法 `stringify_keys'

mysql - 查询运行成功但未找到记录时的响应代码