javascript 对象到 node.js 中的 json 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13782863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Object to json string in node.js
提问by Ajouve
I have a problem with node.js to object to json string
我对 node.js 有问题反对 json 字符串
var chat = {};
chat.messages = [];
chat.messages['en'] = [];
chat.messages['fr'] = [];
console.log(chat.messages)
console.log(JSON.stringify(chat.messages));
I got
我有
[ en: [], fr: [] ]
[]
I don't know why this is not correctly convert
我不知道为什么这不能正确转换
回答by Jon Gauthier
On this line, you initialize chat.messages
as an empty array:
在这一行,你初始化chat.messages
为一个空数组:
chat.messages = [];
Here, you use it as an object:
在这里,您将其用作对象:
chat.messages['en'] = [];
chat.messages['fr'] = [];
These lines actually set properties on the array instance. It's curious that Node would include these properties in the normal .toString()
result (i.e., that you'd see the set properties as elements of the array on console.log(chat.messages)
.
这些行实际上是在数组实例上设置属性。奇怪的是,Node 会将这些属性包含在正常.toString()
结果中(即,您将设置的属性视为console.log(chat.messages)
.
In any case, to fix, declare chat.messages
as an object:
无论如何,要修复,请声明chat.messages
为对象:
chat.messages = {};
chat.messages['en'] = [];
chat.messages['fr'] = [];