简体   繁体   中英

Object to json string in node.js

I have a problem with node.js to object to json string

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

On this line, you initialize chat.messages as an empty array:

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 (ie, that you'd see the set properties as elements of the array on console.log(chat.messages) .


In any case, to fix, declare chat.messages as an object:

chat.messages = {};
chat.messages['en'] = [];
chat.messages['fr'] = [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM