3

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

1
  • I just took a look in my crystal ball, and it says it's not correctly converted because you did'nt feed it the right data ? Commented Dec 8, 2012 at 23:09

1 Answer 1

9

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 (i.e., 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'] = [];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.