views:

1044

answers:

2

Ok so 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 im 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);

        });

If you can help id be very happy :)

+1  A: 

That should work fine. Just use $.getJSON instead of $.get.

Samir Talwar
o yea, but how do i itterate each of the values say i want to get "displayname":"gamers"and echo what should be gamers
ChrisMJ
Your `json` variable will be a JavaScript object. Get it as normal: `for (var user in json.forum) { alert(user.displayname); }`.
Samir Talwar
+1  A: 

To iterate over an array, use a standard for loop with an index. To iterate over object's properties use the 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) {
        alert(property + "=" + object[property]); // 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.

BalusC
ok so i have this, but when i run it, it is printing out Undefined within my <li> tag var url ="forums.json"; $.getJSON (url, function(data){ alert("data loaded"); $.each(data, function(i, item) { $("#forums").html("<li>"+ item.displayname +"</li>") alert("worlds listed"); }); });
ChrisMJ
Replace `$.each(data, ...` by `$.each(data.forum, ...` exactly as in the example. Your `data` is `json` in my example. JSON is an object. The `forum` is a property which contains the array.
BalusC
thank you worked a treat!!!
ChrisMJ
You're welcome.
BalusC