1

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!

3
  • 1
    is the result of the get() an object or a string? Commented Jan 4, 2013 at 12:15
  • Its a string, sorry for not mentioning! Commented Jan 4, 2013 at 12:17
  • 1
    Any chance to see some JavaScript code? jQuery AJAX methods decode JSON automatically... Commented Jan 4, 2013 at 12:17

4 Answers 4

3

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); }); 
Sign up to request clarification or add additional context in comments.

3 Comments

you answered that before me :)
:) just recently faced this prob :D
It seems $ajax is parsing it to string directly, how can i make it an object cuz i was trying your example before asking here and i guess its beacuse it not and object i get undefined...!
2

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

1 Comment

Thanks! I helped me alot with .location.street.id :D!
1

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

1 Comment

JSON and object are contradictory terms. JSON is always a string.
0

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.