Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search JSON tree with jQuery

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.

like image 965
Mentalhead Avatar asked Mar 13 '11 10:03

Mentalhead


People also ask

Can we search in JSON file?

Call a JS function when the user clicks the button. Read the file from disk on the server into a JS variable in the browser. Use lodash. js to get the url from the JS variable for the search term.

How do you split a JSON string in Python?

split('/') call. You will need to check to make sure that len(minMax) == 2 before attempting to add it to the result - and if it is not, add in code that does what you want to do in that case.


2 Answers

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

like image 67
ifaour Avatar answered Sep 21 '22 21:09

ifaour


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         } }); 
like image 41
Tapefreak Avatar answered Sep 23 '22 21:09

Tapefreak