user3770540
user3770540

Reputation: 59

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

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?

Upvotes: 0

Views: 38

Answers (2)

dlopez
dlopez

Reputation: 995

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]));
             }
        }
    });
}

Upvotes: 0

imvain2
imvain2

Reputation: 15847

did you try this?

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

Upvotes: 2

Related Questions