如何使用jQuery搜索JSON树 [英] How to search JSON tree with jQuery
本文介绍了如何使用jQuery搜索JSON树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关于在JSON中搜索特定信息的问题。例如,我有这个JSON文件:
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"
}
]
}
}
我的问题是,如何通过名称查找特定的人并使用jQuery显示该人的年龄?
例如,我想在JSON中搜索名为Peter的人,当我找到匹配项时,我想显示有关该匹配项的其他信息(例如,在本案例中名为Peter的人),例如人的年龄。 / p>
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;
}
});
});
这篇关于如何使用jQuery搜索JSON树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文