I have a JSON array like this:
{ "forum":[ { "id":"1", "created":"2010-03-19 ", "updated":"2010-03-19 ","user_id":"1", "vanity":"gamers", "displayname":"gamers", "private":"0", "description":"All things gaming", "count_followers":"62", "count_members":"0", "count_messages":"5", "count_badges":"0", "top_badges":"", "category_id":"5", "logo":"gamers.jpeg", "theme_id":"1" } ] }
I want to use jQuery .getJSON
to be able to return the values of each of the array values, but I'm not sure as to how to get access to them.
So far I have this jQuery code:
$.get('forums.php', function(json, textStatus) { //optional stuff to do after success alert(textStatus); alert(json); });
How can I do this with jQuery?
The {}
in JSON represents an object. Each of the object's properties is represented by key:value
and comma separated. The property values are accessible by the key using the period operator like so json.forum
. The []
in JSON represents an array. The array values can be any object and the values are comma separated. To iterate over an array, use a standard for loop with an index. To iterate over object's properties without referencing them directly by key you could use for in
loop:
var json = {"forum":[{"id":"1","created":"2010-03-19 ","updated":"2010-03-19 ","user_id":"1","vanity":"gamers","displayname":"gamers","private":"0","description":"All things gaming","count_followers":"62","count_members":"0","count_messages":"5","count_badges":"0","top_badges":"","category_id":"5","logo":"gamers.jpeg","theme_id":"1"}]}; var forum = json.forum; for (var i = 0; i < forum.length; i++) { var object = forum[i]; for (property in object) { var value = object[property]; alert(property + "=" + value); // This alerts "id=1", "created=2010-03-19", etc.. } }
If you want to do this the jQueryish way, grab $.each()
:
$.each(json.forum, function(i, object) { $.each(object, function(property, value) { alert(property + "=" + value); }); });
I've used the same variable names as the "plain JavaScript" way so that you'll understand better what jQuery does "under the hoods" with it. Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With