Chris G.
Chris G.

Reputation: 339

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

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?

Upvotes: 1

Views: 4246

Answers (2)

Tim Vermaelen
Tim Vermaelen

Reputation: 7059

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

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114377

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.

Upvotes: 1

Related Questions