1

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

6
  • Still not clear what exactly you want.. "...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." Commented Jun 14, 2015 at 4:15
  • You want to print just honda or all the values of 'name' attribute ? Commented Jun 14, 2015 at 4:18
  • @ChintanSoni sorry if I didn't explain good enough myself (not a native english speaker)... I want to print all values of 'name' attribute. I'm not able to loop trough all of this 'name' attributes with my current code Commented Jun 14, 2015 at 4:20
  • And when I use the codes in the answers already given, I get "undefined" on the browser's console if I do console.log(val.name) Commented Jun 14, 2015 at 4:21
  • Daniel, provide your "/document/location" content, what their content ?, show it Commented Jun 14, 2015 at 4:21

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Using your code I'm doing a console.log(val.name) and I get undefined on my Chrome browser console
Thank you, it works as expected now, I had to leave (key, val) on the $.each line instead of just (val) as someone here mentioned. Again, many thanks
3

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>';    
}

2 Comments

thank you but who is data? I'm accessing to an external document, data is not a local variable
data is the variable you stored your response to. I din't mentioned the whole code but just the snippet for you to understand :)
1

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

1 Comment

Using your code I'm doing a console.log(val.name) and I get undefined on my Chrome browser console
1

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..

Comments

1

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

2 Comments

This is actually great info! thanks, I'm currently using pretty complex code with Google maps and I think I wouldn't know how to implement this but I will try. Again, thanks :)
Me gusta ayudar a quien lo necesite :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.