如何使用 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 的人),例如人的年龄.
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屋!
查看全文