0

Possible Duplicate:
Accessing elements of JSON object without knowing the key names

I have this below json. Using this i need to iterate over this and push then into an array as key value, trouble is that this json will come at runtime and i won't know the name of the key.

MethodParam : [
        {MaxNumberOfDomains : '10'}, 
        {NextToken : '1'}
]

please advise

thanks

Community
  • 1
  • 1
Amit
  • 6,839
  • 21
  • 56
  • 90
  • That looks like a part of a JavaScript object, not JSON. In any case, once you parsed the JSON your problem is not not related to JSON anymore but to JavaScript only. In this case you want to know how to get the property names of an object. – Felix Kling Mar 09 '12 at 09:22
  • @Felix, Do you have an answer on how to achieve this? – Amit Mar 09 '12 at 09:25
  • @Amit, see the question Felix said was a duplicate. It should give you your answer. – GregL Mar 09 '12 at 09:26

1 Answers1

0

Here's one way of doing it.

// First, let's have some variables and your example object/json:
var i, l, key, item = [ {keyOne: 10}, {keyTwo: 'string', keyThree: false} ];
// The example you provided is an array, so we first loop that array of objects/json objects
for (i = 0, l = item.length; i < l; i++) {
    // Now, let's see all the keys in the current object
    console.log('Iterating array ' + (i + 1));
    for (key in item[i]) {
        console.log(key);
    }
}

When I run this in node v0.6.11, I get this:

node
> // First, let's have some variables and your example object/json:
undefined
> var i, l, key, item = [ {keyOne: 10}, {keyTwo: 'string', keyThree: false} ];
undefined
> // The example you provided is an array, so we first loop that array of objects/json objects
undefined
> for (i = 0, l = item.length; i < l; i++) {
...     // Now, let's see all the keys in the current object
...     console.log('Iterating array ' + (i + 1));
...     for (key in item[i]) {
.....         console.log(key);
.....     }
... }
Iterating array 1
keyOne
Iterating array 2
keyTwo
keyThree
undefined
> 
Zlatko
  • 18,936
  • 14
  • 70
  • 123