How to search JSON tree using jQuery

I have a question about finding JSON for 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 I find a specific person by name and show the age of that person using jQuery? For example, I want to find JSON for a person named Peter, and when I find a match, I want to display additional information about this match (for example, about a person named Peter), for example, about the age of the person.

+64
json javascript jquery search tree
Mar 13 '11 at 10:35
source share
11 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; } }); 

An example .

Based on this answer , you can 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

+91
Mar 13 2018-11-11T00:
source share

I found an ifaour jQuery.each () example to be useful, but would add that jQuery.each () could get corrupted (i.e. stopped), returning false at the point where you found what you are looking for:

 $.each(json.people.person, function(i, v) { if (v.name == "Peter") { // found it... alert(v.age); return false; // stops the loop } }); 
+19
Aug 23 '11 at 15:00
source share

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

It uses a true XPath engine and has extensive customization options. It works both in Node.js and in the browser.

Given your original question, you will find people named 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've always worked with the same JSON schema, you can create your own schema using jsel and be able to use shorter expressions, such as:

 dom.select("//person[@name='Peter']") 
+11
Aug 13 '13 at 4:45
source share

Once you load JSON into a JavaScript object, this is no longer a jQuery problem, but now a JavaScript problem. In JavaScript, you can, for example, write a search, for example:

 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 ! 
+9
Mar 13 '11 at 10:41
source share

There are several js libraries that could help you:

You can also take a look at Lawnchair , which is a JSON-Document-Store that runs in a browser and has all kinds of request mechanisms.

+7
Mar 13 2018-11-11T00:
source share

You can use DefiantJS ( http://defiantjs.com ), which extends the global JSON object with a search method. With which you can query XPath requests in JSON structures. Example:

 var byId = function(s) {return document.getElementById(s);}, data = { "people": { "person": [ { "name": "Peter", "age": 43, "sex": "male" }, { "name": "Zara", "age": 65, "sex": "female" } ] } }, res = JSON.search( data, '//person[name="Peter"]' ); byId('name').innerHTML = res[0].name; byId('age').innerHTML = res[0].age; byId('sex').innerHTML = res[0].sex; 

Here is a working fiddle;
http://jsfiddle.net/hbi99/NhL7p/

+7
Jan 05 '14 at
source share

You can search in an array of json objects using $ .grep () as follows:

 var persons = { "person": [ { "name": "Peter", "age": 43, "sex": "male" }, { "name": "Zara", "age": 65, "sex": "female" } ] } }; var result = $.grep(persons.person, function(element, index) { return (element.name === 'Peter'); }); alert(result[0].age); 
+7
Mar 26 '15 at 2:04
source share
  var GDNUtils = {}; GDNUtils.loadJquery = function () { var checkjquery = window.jQuery && jQuery.fn && /^1\.[3-9]/.test(jQuery.fn.jquery); if (!checkjquery) { var theNewScript = document.createElement("script"); theNewScript.type = "text/javascript"; theNewScript.src = "http://code.jquery.com/jquery.min.js"; document.getElementsByTagName("head")[0].appendChild(theNewScript); // jQuery MAY OR MAY NOT be loaded at this stage } }; GDNUtils.searchJsonValue = function (jsonData, keytoSearch, valuetoSearch, keytoGet) { GDNUtils.loadJquery(); alert('here' + jsonData.length.toString()); GDNUtils.loadJquery(); $.each(jsonData, function (i, v) { if (v[keytoSearch] == valuetoSearch) { alert(v[keytoGet].toString()); return; } }); }; GDNUtils.searchJson = function (jsonData, keytoSearch, valuetoSearch) { GDNUtils.loadJquery(); alert('here' + jsonData.length.toString()); GDNUtils.loadJquery(); var row; $.each(jsonData, function (i, v) { if (v[keytoSearch] == valuetoSearch) { row = v; } }); return row; } 
+2
Feb 02 2018-12-12T00:
source share

I have a similar condition plus my search query, not limited to the specific Object property (for example, "John", the search query must match the first_name, as well as the last_name property). After spending several hours, I got this feature from an Angular project. They took care of all possible cases.

 /* Seach in Object */ var comparator = function(obj, text) { if (obj && text && typeof obj === 'object' && typeof text === 'object') { for (var objKey in obj) { if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) && comparator(obj[objKey], text[objKey])) { return true; } } return false; } text = ('' + text).toLowerCase(); return ('' + obj).toLowerCase().indexOf(text) > -1; }; var search = function(obj, text) { if (typeof text == 'string' && text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return comparator(obj, text); case "object": switch (typeof text) { case "object": return comparator(obj, text); default: for (var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } break; } return false; case "array": for (var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; 
+2
Jun 20 '14 at 10:11
source share

Go through all the nodes of the JSON object tree using JavaScript

0
Mar 13 2018-11-11T00:
source share

You do not need to use jQuery. Simple JavaScript will work. I would not recommend any library that portes XML standards to JavaScript, and I was disappointed that there was no other solution for this, so I wrote my own library.

I adapted the regular expression to work with JSON.

First we contract the JSON object. Then you need to keep the starting and long matching substrings. For example:

 "matched".search("ch") // yields 3 

For a JSON string, this works the same way (unless you explicitly look at the commas and braces, in which case I would recommend some preliminary conversion of your JSON object before executing the regular expression (ie think :, {,}).

Then you need to restore the JSON object. The algorithm I created does this by detecting the JSON syntax by recursively jumping back from the matching index. For example, a pseudo code might look like this:

 find the next key preceding the match index, call this theKey then find the number of all occurrences of this key preceding theKey, call this theNumber using the number of occurrences of all keys with same name as theKey up to position of theKey, traverse the object until keys named theKey has been discovered theNumber times return this object called parentChain 

Using this information, you can use a regular expression to filter a JSON object to return the key, value, and parent chain of objects.

You can see the library and code that I wrote at http://json.spiritway.co/

0
Mar 28 '15 at 2:44
source share



All Articles