How to search JSON tree with jQuery
Once you have the JSON loaded into a JavaScript object, it's no longer a jQuery problem but is now a JavaScript problem. In JavaScript you could for instance write a search such as:
var people = myJson["people"];
var persons = people["person"];
for(var i=0; i < persons.length; ++i) {
var person_i = persons[i];
if(person_i["name"] == mySearchForName) {
// found ! do something with 'person_i'.
break;
}
}
// not found !
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
}
});
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
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']")