userimage

Find conditional data from JSON tree using jQuery

I have the below JSON Tree structure and my question from this is how can find a particular person by name and display that person"s age with jQuery?

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

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.

userimage

First of all keep your structure in a variable and iterate like ,

$.each(json.people.person, function(i, v) {
    if (v.name == "Peter") {
        alert(v.age);
        return;
    }
});

or else find another example based on your search,


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



Answer is