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.
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.
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.
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 } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With