0

How do I change a JSON object into an array key/value pairs through code?

from:

{
   'name':'JC',
   'age':22
}

to:

['name':JC,'age':22] //actually, see UPDATE


UPDATE:

...I meant:

[{"name":"JC"},{"age":22}]

5
  • 3
    That is an invalid array. Did you mean: ["name","JC","age",22] or [{"name":"JC"},{"age":22}]? Commented Mar 7, 2012 at 23:41
  • Yes it is Rob! @Jan: maybe this helps: stackoverflow.com/questions/558981/… Commented Mar 7, 2012 at 23:42
  • To expand on @RobW's point, Javascript does not have associative arrays (like PHP), it uses objects. They have a few key limitations, but work in a very similar way. Maybe it would help to know why you are looking for this type of construct? Commented Mar 7, 2012 at 23:43
  • @Morgon: just out of curiosity actually.. Commented Mar 7, 2012 at 23:44
  • @RobW: hmm... so if that's the case, how would I do that through code? Commented Mar 7, 2012 at 23:45

3 Answers 3

1

May be you only want understand how to iterate it:

var obj = { 'name':'JC', 'age':22 };
for (var key in obj)
{
    alert(key + ' ' + obj[key]);
}

Update:
So you create an array as commented:

var obj = { 'name':'JC', 'age':22 };
var obj2 = [];
for (var key in obj)
{
    var element = {};
    element[key] = obj[key]; // Add name-key pair to object
    obj2.push(element);      // Store element in the new list
}
Sign up to request clarification or add additional context in comments.

1 Comment

well I want to put it into one BIG array containing many objects.. like [{..},{..}] with one Object per property..
1

If you're trying to convert a JSON string into an object, you can use the built in JSON parser (although not in old browsers like IE7):

JSON.parse("{\"name\":\"JC\", \"age\":22}");

Note that you have to use double quotes for your JSON to be valid.

Comments

0

There is no associative array in JavaScript. Object literals are used instead. Your JSON object is such literal already.

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.