noa-dev noa-dev - 1 year ago 103
JSON Question

JSON.parse is removing 2 objects from JSON object

I am currently experiencing this weird issue.

I have a valid JSON object just like this:

var myjson = '[{"text": {"tag": "question","content": "question content 1"}}, {"text": {"tag": "answer","content": "answer content1"},"text": {"tag": "question","content": "question content 2"},"text": {"tag": "answer","content": "answer content2"}}]';

Then I proceed to transform it into a normal javascript array of objects like so:

var parsed = JSON.parse(myjson);

For some weird reason the parsed Array only contains the first and last object ....

I have prepared a fiddle for this here

Answer Source

You use the same key multiple times, the last one will overwrite all previous ones. Use unique keys or put the values of those keys in an array instead. In this post there is a link to the original spec declaring that this should be the case.

Edit: here's an example fiddle

var myjson = '[{"text": {"tag": "question","content": "question content 1"}}, {"text1": {"tag": "answer","content": "answer content1"},"text2": {"tag": "question","content": "question content 2"},"text3": {"tag": "answer","content": "answer content2"}}]';

// OR
var myjsonarray = '[{"text": {"tag": "question","content": "question content 1"}}, [{"tag": "answer","content": "answer content1"}, {"tag": "question","content": "question content 2"},{"tag": "answer","content": "answer content2"}]]'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download