How to search JSON tree with jQuery

Mentalhead picture Mentalhead · Mar 13, 2011 · Viewed 241.5k times · Source

I have a question about searching the JSON for the specific information. For example, I have this JSON file:

 {
    "people": {
        "person": [
            {
                "name": "Peter",
                "age": 43,
                "sex": "male"
            }, {
                "name": "Zara",
                "age": 65,
                "sex": "female"
            }
        ]
    }
}

My question is, how can find a particular person by name and display that person's age with jQuery? For example, I want to search the JSON for a person called Peter and when I find a match I want to display additional information about that match (about person named Peter in this case) such as person's age for example.

Answer

ifaour picture ifaour · Mar 13, 2011
var json = {
    "people": {
        "person": [{
            "name": "Peter",
            "age": 43,
            "sex": "male"},
        {
            "name": "Zara",
            "age": 65,
            "sex": "female"}]
    }
};
$.each(json.people.person, function(i, v) {
    if (v.name == "Peter") {
        alert(v.age);
        return;
    }
});

Example.

Based on this answer, you could use something like:

$(function() {
    var json = {
        "people": {
            "person": [{
                "name": "Peter",
                "age": 43,
                "sex": "male"},
            {
                "name": "Zara",
                "age": 65,
                "sex": "female"}]
        }
    };
    $.each(json.people.person, function(i, v) {
        if (v.name.search(new RegExp(/peter/i)) != -1) {
            alert(v.age);
            return;
        }
    });
});

Example 2