Daniel Daniel - 5 months ago 10
JSON Question

jQuery: Loop through JSON document

I have the following JSON structure on "y" location:

{"results":[{
"a_id":4529245,
"type":"a",
"name":"HONDA"
},{
"a_id":1234567,
"type":"l",
"name":"Autos Marron"
}]}


Inside my JS document I have the following code:

var i;
i=0;
$.getJSON('/document/location', function( data ) {

console.log(data);

$.each( data, function( key, val ) {

var contentString = '<span>'+
val[i].name +
'</span>';

$('#info').append(contentString);

i++;
});
});


I searched online and I readed that I would be able to do val.name and would be able to print each of the "name" variables inside my JSON document.

But I have to use a incrementing variable (i) in order to print only the first variable that equals to "HONDA" using val[i].name

I'd like to print all variables called name. What am I doing wrong?

Thanks in advance

A.J A.J
Answer

You need to loop data.results as this is the array you want to access:

Code

$.getJSON('/document/location', function( data ) {

    console.log(data);

    $.each( data.results, function(key,val ) {

        var contentString = '<span>'+
        val.name +
        '</span>';

        $('#info').append(contentString);

    });
});

** In your code when you loop through data you get:

val as

[{
            "a_id":4529245,
            "type":"a",
            "name":"HONDA"
        },{
            "a_id":1234567,
            "type":"l",
            "name":"Autos Marron"
        }]

and key as results

Now since val is an array to display name you had to do data[index].name

Edit:

Here is working fiddle

Comments