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}]

Jan Carlo Viray
  • 11,856
  • 11
  • 42
  • 63
  • 3
    That is an invalid array. Did you mean: `["name","JC","age",22]` or `[{"name":"JC"},{"age":22}]`? – Rob W Mar 07 '12 at 23:41
  • Yes it is Rob! @Jan: maybe this helps: http://stackoverflow.com/questions/558981/iterating-through-list-of-keys-for-associative-array-in-json – androidavid Mar 07 '12 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? – Morgon Mar 07 '12 at 23:43
  • @Morgon: just out of curiosity actually.. – Jan Carlo Viray Mar 07 '12 at 23:44
  • @RobW: hmm... so if that's the case, how would I do that through code? – Jan Carlo Viray Mar 07 '12 at 23:45

3 Answers3

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.

Alex Korban
  • 14,916
  • 5
  • 44
  • 55
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
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
freedev
  • 25,946
  • 8
  • 108
  • 125
0

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

Marat Tanalin
  • 13,927
  • 1
  • 36
  • 52