Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery loop through json?

Tags:

json

jquery

each

I have some json (var data)that looks like this:

{"success":"true","keywords":["firstkeyword","secondkeyword"]}

And im trying to loop through the keywords using this code:

            data.keywords.each(function(e){
                $('#campaign_keywords').append("<p>"+e+"</p>");
            });

But i get the error

Uncaught TypeError: Object firstkeyword,secondkeyword has no method 'each' 
like image 304
Jonah Katz Avatar asked Dec 20 '12 20:12

Jonah Katz


People also ask

How to loop through object in jQuery?

The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

Can you loop through json object JavaScript?

Looping Using JSON JSON stands for JavaScript Object Notation. It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values.

How to loop array in jQuery?

Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.


3 Answers

You need to loop through it like this:

$.each(data.keywords, function (i, v) {
    $('#campaign_keywords').append("<p>"+data.keywords[i]+"</p>");
});

jQuery.each()

like image 82
PhearOfRayne Avatar answered Oct 10 '22 23:10

PhearOfRayne


That's because it's an array and it needs to be a jquery wrapped object in order to use jquery functions. Try:

$.each(data.keywords, function(index, value){...});
like image 35
Jason Whitted Avatar answered Oct 10 '22 23:10

Jason Whitted


Its a javascript array, not jQuery object. just apply $ over it to make it jquery object like

    $(data.keywords).each(function(e){
        $('#campaign_keywords').append("<p>"+e+"</p>");
    });
like image 44
Sarim Avatar answered Oct 11 '22 00:10

Sarim