Bertho Joris Bertho Joris - 3 months ago 18
jQuery Question

jQuery how to get data from json with multiple loop

I have json data like this http://pastebin.com/k3a5UNsL
enter image description here
When viewed using the json formater, I want to take the data stored on the object using jquery inside possible_persons object.

I'm trying to loop into the data, but confused how do I get the data names, gender, addresses, etc...
enter image description here
enter image description here

When I use this code

function build_possible_persons(result) {
var relationship = result['possible_persons'];
$.each(relationship, function(key, value) {
$.each(value, function(sec_key, sec_value) {
alert(sec_value);
});
});
}


I get a result of the alert value of the results of the first loop, which as shown in Figure 0:25, 3788825f48716e6c ...., [object], [object], etc ....

How can I do a looping into the objects in it in order to get the value I want?
I try

function build_possible_persons(result) {
var relationship = result['possible_persons'];
$.each(relationship, function(key, value) {
$.each(value, function(sec_key, sec_value) {
$.each(sec_key.names, function(third_key, third_value) {
alert(third_key);
});
});
});
}


or use

alert(sec_key.names[0].display);


But no luck. The code that I create show no results.

Please help to see the flaws in my code. Thanks

Answer

The first problem I see is that in your second loop's sec_key is the text "names" (as well as your other properties. If you want to loop over names replace with:

$.each(value['names'], function(j, name)

Second problem: not all of your relationships have a property names so you need to check for this:

if(value['names']) {
    $.each(value['names'], function(....

finally each "name" is an object that has properties first and last. If you alert an object you're not going to see the actual names. You should make sure of the display property you have set or reconstruct the string

Bringing it all together:

$.each(relationship, function(i, value) {
    if (value['names'] !== undefined) {
        $.each(value['names'], function(j, name) {
            console.log(name.display);
        });
    }
});