Daniel
Daniel

Reputation: 376

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

Upvotes: 1

Views: 98

Answers (5)

vs_lala
vs_lala

Reputation: 735

Why not you make a simple for loop instead of using $.each.

Try this:

for(int i=0;i<data.length;i++){
    var contentString = '<span>'+
    data[i].name +
    '</span>';    
}

Upvotes: 3

ArcangelZith
ArcangelZith

Reputation: 101

Having the following structure

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

For a string better performance try

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

    var buffer = [];

    $.each( data.results, function( index, entry )
    {
        buffer.push( '<span>', entry.name, '</span>' );
    });

    $('#info').append( buffer.join('') );
});

For safe code (to prevent injection) with better performance try

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

    var box = document.createDocumentFragment();

    $.each( data.results, function( index, entry )
    {
        $( '<span>' ).text( entry.name ).appendTo( box );
    });

    $('#info').append( box );
});

Test safe and unsafe code in fiddle

Upvotes: 1

Chintan Soni
Chintan Soni

Reputation: 25267

Ok.. First if all, if you are having .json file in other folder then, specify path to it:

Say, your directory structure is like:

|---data
    |---test.json
|---js
|---css
|---index.html

Then, your code looks like:

$.getJSON("data/test.json", function(json) {
    console.log(json); // this will show the info it in firebug console

    var tempData = "";
    $.each( json.results, function(index, element) {
        tempData  += '<span>'+element.name +'</span>';
    });
    $('#info').html(tempData);
});

Note: Its not good habit of traversing DOM for every element in loop. Like I saw in other answers. Say you got 100 elements in your array, then its worthless traversing DOM 100 times just to append 1 data at a time. So, you can optimise this to having variable that holds the data to be displayed in html, and after looping over the array, just use .append("") or .html("") depending on your need. Hope you got it..

Upvotes: 1

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

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

Upvotes: 3

squill25
squill25

Reputation: 1208

Try this:

$.each( data.results, function( val ) { // change data to data.results, and you are looping through an array so there is no key; only a val

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

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

    // i++; You don't need i at all
});

Upvotes: 1

Related Questions