Nikolay Lapitskiy
Nikolay Lapitskiy

Reputation: 975

Serializing object with arrays with objects to JSON in javascript

I have an object like this:

obj = {"arr1" : [], "arr2" : ['z1', 'z2', 'z3'], "arr3" : []};
obj['arr2']['z2'] = 'z8';

It has nested arrays, and each value of can be an object with or without arrays, etc.

How to get a JSON for that? JSON.stringify would lose 'z8' value.

Upvotes: 1

Views: 910

Answers (2)

Minko Gechev
Minko Gechev

Reputation: 25682

In JSON (by standard) you have Arrays, Objects, values and strings, arrays are not Objects like in JavaScript. JSON is only a data-interchange format, you don't have a base prototype like in JavaScript where almost everything is an object and have properties.

So, if you want to have a property z3 of z2 you have to make z2 an object.

Upvotes: 3

Selvaraj M A
Selvaraj M A

Reputation: 3136

arr2 is an array. You cannot use it like a map.

var obj = {"arr1" : [], "arr2" : ['z1', {'z2':'z3'}], "arr3" : []};
obj['arr2'][1]["z2"] = 'z8';
alert(JSON.stringify(obj));​

Fiddle

Upvotes: 2

Related Questions