Reputation: 12712
my explorations into jquery are proving a little frustrating.
I am receiving the following Json back from the server.
{"status":"ok",
"0":{"ID":"1","location":"location info"},
"1":{"ID":"2","location":"location info"},
"2":{"ID":"3","location":"location info"},
...etc
});
I need to put all the objects except the status into an array. I achieved this in AS3 as follows, but don't seem to be able to get any where near using jquery.
public function ResultToArray(jsonString:String):Array
{
var jObj:Object = JSON.decode(jsonString);
var objects:Array = [];
for each(var obj:Object in jObj)
{
if(obj is String)break;
objects.push(obj);
}
return objects;
}
I would like to put each of the objects in an array.
The following only loops over one object.
$(data).each(function(index)
{
alert(data[index]["location"])
});
Please pardon my ignorance. If I could receive any advice It'd be much appreciated.
Upvotes: 0
Views: 1371
Reputation: 19423
var o = jQuery.parseJSON(jsonString),
myObjects = [];
for (var c in o) {
if (c != 'status')
myObjects.push(o[c]);
}
Possibly you could check (typeof o[c] == 'object')
if you don't want to check for 'status'.
Upvotes: 2
Reputation: 53198
If I understand well, your JSON could be improved to help you out here. Instad of storing each location as a zero-based integer index, why not store them in a JSON array:
{
"status":"ok",
"locations":[
{ "ID":"1", "location":"location info"},
{ "ID": "2", "location": "location info" },
{ "ID": "2", "location": "location info" },
...etc
]
}
Then, with jQuery all you need to do is parse the JSON and extract the location
parameter, which is already an array:
// Assume jsonString is retrieved from an AJAX call:
var locationObj = $.parseJSON(jsonString);
var locations = locationObj.locations;
Upvotes: 4
Reputation: 14827
You can use jQuery.getJSON() to fetch data remotely and have it turned into a Javascript object.
Upvotes: 1