C Bauer
C Bauer

Reputation: 5113

Using jQuery to process a JSON object

My JSON object is constructed like this:

var Source =
{
    Object: [ //Array
        {Title: 'Test', Type: 'Pet', Category: 'Cat', Description: 'Fluffy', Count: 2 }
    ]
};

I was able to figure out how to properly add to the 'Object' array, but I can't seem to figure out the jQuery syntax to query the object based on the property list (Title, Type, Category, etc).

I put some test code into a click event and normally check the length of the Source.Object (Test data results in 2 objects) to confirm that there is data to work with (It's populated through an ajax call).

function clickTest(category, type) {
    $(Source).find('Object[Category=\"' + category + '\"]').each(function() {
        alert($(this).attr('Category')); //doesn't work
    });
}

What is the right way to query a JSON object like this?

Upvotes: 1

Views: 7979

Answers (3)

Alex Gyoshev
Alex Gyoshev

Reputation: 11967

JSON is native to JavaScript and can be cycled through without the use of libraries (jQuery). The [] represent arrays, and {} represent objects, therefore:

var obj = Source.Object;
for (var i = 0, len = obj.length; i < len; i++) {
    if (obj[i].Category == category)
        alert(obj[i].Category + ' ' + obj[i].Title);
}

And that's faster, too! Good stuff.

Upvotes: 7

samy
samy

Reputation: 14972

JSon is a way to transcribe a javascript object in a string format and transmit it on the wire. One nice thing about the format is that it's directly readable by javascript, so your Source object is already ready to be processed.

function processSource(source, category)
{
    var counter = 0;
    for (counter = 0; counter < source.Object.length; counter += 1)
    {
        if (category === source.Object[counter].category) {
           // do something
        }
    }
}

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328850

The source is a JSON object, not a HTML DOM. Therefore, you must use the jQuery utility functions for arrays:

$.grep( Source.Object, function(e) { return e.Category == category } ).each(...)

Upvotes: 5

Related Questions