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.
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;
}
});
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;
}
});
});