How to parse JSON data when the property name is not known in advance?

17,624

Solution 1

Use Object.keys to retrieve a full list (array) of key names. A polyfill is available here.

var group = response.groupIds[i];

var allPropertyNames = Object.keys(group);
for (var j=0; j<allPropertyNames.length; j++) {
    var name = allPropertyNames[j];
    var value = group[name];
    // Do something
}

Your question's response format contains only one key-value pair. The code can then be reduced to:

var group = response.groupIds[i];
var name = Object.keys(group)[0]; // Get the first item of the list;  = key name
var value = group[name];

If you're not interested in the list, use a for-i-in loop with hasOwnProperty. The last method has to be used, to exclude properties which are inherit from the prototype.

for (var name in group) {
    if (group.hasOwnProperty(name)) {
        var value = group[name];
        // Do something
    }
}

Solution 2

Use a for..in loop:

for( x in response.groupIds[i]) {
    // x is now your unknown key
    // response.groupIds[i][x] is the unknown value
}

Since there is only one property of the object, that'll work nicely.

Share:
17,624
David Willis
Author by

David Willis

Updated on June 23, 2022

Comments

  • David Willis
    David Willis almost 2 years

    Here is my response code in jQuery:

    var response = $.parseJSON(response);
    
    for (var i = 0; i < response.groupIds.length; i++) {
        console.log(response.groupIds[i], i);
    }
    

    Each response.groupIds[i] is of the form {"unknown name":"unknown value"}.

    I wish to access both of these bits of data in javascript, how do I accomplish this when I don't know in advance what e.g. unknown name is?

  • David Willis
    David Willis about 12 years
    When I try this it says i is not defined?
  • Niet the Dark Absol
    Niet the Dark Absol about 12 years
    Didn't you define it in your first for loop?