解析JSON字符串的最佳方法是什么?

解析JSON字符串的最佳方法是什么?

问题描述:

我使用 $。getJSON 生成了一个JavaScript对象(称之为'jItems')。在页面上,我有一个jItems中的项目适合的类别列表。我的愿望是单击一个类别并触发一个功能,只显示该类别中的项目。使用 getJson 或jquery的每个() find() jItems 中提取正确的项目?

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?

这一切都取决于你的数据如何,但这可能对你有所帮助:

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);
        }
    });
});

要查看示例: http://jsfiddle.net/tive/U63EY/

编辑:
现在我再次阅读你的问题...实际上,使用for循环更好,因为这样更快。 $ .each()无论如何都是for循环的包装器。 (因此示例:D)

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