Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
5  
Your object is invalid: arr2 should be an object, not an array. –  VisioN Dec 20 '12 at 12:08
1  
Have you tried to execute this code? The first line isn't even valid JavaScript. –  James McLaughlin Dec 20 '12 at 12:10
    
To elaborate on @VisioN's comment: In JavaScript, Objects always have a combination of key:value, Arrays never do. –  Cerbrus Dec 20 '12 at 12:11
    
Fixed the object –  Lapa Dec 20 '12 at 12:26

2 Answers 2

up vote 2 down vote accepted

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.

share|improve this answer
    
Thanks, that works. –  Lapa Dec 21 '12 at 9:22

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.