Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 551
David Willis Avatar asked Mar 15 '12 21:03

David Willis


People also ask

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.

How do you access properties of JSON objects?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

Is JSON () the same as JSON parse?

The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).

Is JSON parsed automatically?

The json auto operator automatically detects where the JSON object is located and parses it.


2 Answers

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
    }
}
like image 52
Rob W Avatar answered Nov 15 '22 21:11

Rob W


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.

like image 20
Niet the Dark Absol Avatar answered Nov 15 '22 19:11

Niet the Dark Absol