What's the best way to parse a JSON string?

点点圈 提交于 2019-12-11 13:47:18

问题


I've generated a JavaScript object (call it 'jItems') using $.getJSON. On the page, I've got a list of categories that the items in jItems fit into. My desire is to click a category and trigger a function to display only the items in that category. Would it be better to use getJson or jquery's each() or find() to pull the right items from jItems?


回答1:


It all depends on how your data looks like but this might help you I think:

var jsonCats = [
    {"id": "category1", "items": [{"iid":"item1"}, {"iid":"item2"}, {"iid":"item3"}]},
    {"id": "category2", "items": [{"iid":"item4"}, {"iid":"item5"}, {"iid":"item6"}]},
    {"id": "category3", "items": [{"iid":"item7"}, {"iid":"item8"}, {"iid":"item9"}]},
    {"id": "category4", "items": [{"iid":"item0"}]}
];

$.each(jsonCats, function(key, value) {
    var category = $("<li>" + this.id + "</li>");
    var items = this.items;

    $("#categories").append(category);

    category.click(function() {
        $("#items").empty();
        for (var j in items) {
            var item = $("<option>" + items[j].iid + "</option>");

            $("#items").append(item);
        }
    });
});

To see an example: http://jsfiddle.net/tive/U63EY/

EDIT: Now I read your question again ... it's actually better to use for loops since this is faster. The $.each() is a wrapper of the for loop anyway. (Hence the example :D)

http://jsperf.com/jquery-each-vs-for-loop/6




回答2:


The beauty of JSON is you don't need to parse it. It's already a JavaScript object. What you need to do is loop through the values and build the output for your category list.

Without seeing your JSON structure I cannot make any more recommendations.



来源:https://stackoverflow.com/questions/11727316/whats-the-best-way-to-parse-a-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!