Rovdjuret
Rovdjuret

Reputation: 1528

Iterate through JSON

i'm wondering how i could loop through this json data to get the values inside it with jquery? All i've got is undefined. I'm using $.ajax.get() to get the file then i'm trying to loop through it to get data inside it. The JSON looks like this...

The result from the get is a string!

    [
    {
        "category": "anti-social-behaviour", 
        "persistent_id": "", 
        "location_subtype": "STATION", 
        "month": "2012-11", 
        "location": {
            "latitude": "52.6313999", 
            "street": {
                "id": 1447707, 
                "name": "Leicester"
            }, 
            "longitude": "-1.1252999"
        }, 
        "context": "", 
        "id": 18782816, 
        "location_type": "BTP", 
        "outcome_status": {
            "category": "Under investigation", 
            "date": "2012-11"
        }
    }
]

Regards /Haris!

Upvotes: 1

Views: 114

Answers (4)

palaѕн
palaѕн

Reputation: 73906

You can simply loop through the items like this:

$.each(obj, function(i, val) {
    alert(val.category);
    alert(val.location.latitude);
    alert(val.location.street.id);
});​

DEMO HERE

Upvotes: 2

Rovdjuret
Rovdjuret

Reputation: 1528

Seems the problem was it of course wasn't an object and thats why i couldnt interate through the json... So i used: var obj = jQuery.parseJSON();

and everything works perfectly!

Upvotes: 0

Saligor
Saligor

Reputation: 78

You need to be sure that you have a json object and not a string. After:

for(var i in JSONObject){ // code goes here }

Remember that you can also call the elements in the object using it direct key value.

Exp. ObjName.keyname

Upvotes: 1

sk8terboi87  ツ
sk8terboi87 ツ

Reputation: 3457

Lets say you're getting through ajax call and youre json returned is on some var data, you can parse using $.each

$.each(data, function(i, obj) {
  //use obj.id and obj.name here, for example:
  alert(obj.name);
});

Upvotes: 3

Related Questions