JSON and Javascript - Can't pull nested data from JSON

39 views Asked by At

OK, so i'm trying to loop over and pull "title" out of an API using javascript, API looks like this in console:

Object {status: "ok", data: Array[28]}
data:Array[28]
    0:Object    
        age_restricted:true
        always_on_menu:false
        box_limit:"2"
        id:"1907b434-f71d-11e5-887e-02787aad01f3"
        is_for_sale:true
        is_vatable:true
        list_price:"7.95"
        sku:"AP-ACH-WIN-WHI-06-P"
        title:" Camino Real Blanco Rioja"

Javascript as follows:

$.getJSON("URL", callbackData);

function callbackData(data) {
    for (var key in data) {
        var obj = data[key];
        for (var prop in obj) {
             if (obj.hasOwnProperty(prop)) {
            document.write(JSON.stringify(prop));
        }
    }
}
}

But all I get is the Key so in this case the 0 come out.

Any ideas?

2

There are 2 answers

1
imvain2 On BEST ANSWER

did you try this?

document.write(JSON.stringify(obj[prop]));
0
dlopez On

Data is an array, so the proper way to iterate through it is with forEach. Anyway, the value that you want to get is obj[prop].

function callbackData(data) {
    data.forEach(function(obj) {
        for (var prop in obj) {
             if (obj.hasOwnProperty(prop)) {
                 document.write(JSON.stringify(obj[prop]));
             }
        }
    });
}