How to search JSON tree with jQuery How to search JSON tree with jQuery json json

How to search JSON tree with jQuery


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


I found ifaour's example of jQuery.each() to be helpful, but would add that jQuery.each() can be broken (that is, stopped) by returning false at the point where you've found what you're searching for:

$.each(json.people.person, function(i, v) {        if (v.name == "Peter") {            // found it...            alert(v.age);            return false; // stops the loop        }});


You could use Jsel - https://github.com/dragonworx/jsel (for full disclosure, I am the owner of this library).

It uses a real XPath engine and is highly customizable. Runs in both Node.js and the browser.

Given your original question, you'd find the people by name with:

// include or require jsel library (npm or browser)var dom = jsel({    "people": {        "person": [{            "name": "Peter",            "age": 43,            "sex": "male"},        {            "name": "Zara",            "age": 65,            "sex": "female"}]    }});var person = dom.select("//person/*[@name='Peter']");person.age === 43; // true

If you you were always working with the same JSON schema you could create your own schema with jsel, and be able to use shorter expressions like:

dom.select("//person[@name='Peter']")