Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

jQuery parse JSON multidimensional array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...