Javascript 如何使用 jQuery 搜索 JSON 树
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5288833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to search JSON tree with jQuery
提问by Mentalhead
I have a question about searching the JSON for the specific information. For example, I have this JSON file:
我有一个关于在 JSON 中搜索特定信息的问题。例如,我有这个 JSON 文件:
{
"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.
我的问题是,如何通过姓名找到特定的人并使用 jQuery 显示该人的年龄?例如,我想在 JSON 中搜索一个名为 Peter 的人,当我找到一个匹配项时,我想显示有关该匹配项的其他信息(在本例中是关于名为 Peter 的人),例如人的年龄。
回答by ifaour
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;
}
});
});
回答by Tapefreak
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:
我发现 ifaour 的 jQuery.each() 示例很有帮助,但会补充说 jQuery.each() 可以通过在您找到要搜索的内容时返回 false 来破坏(即停止):
$.each(json.people.person, function(i, v) {
if (v.name == "Peter") {
// found it...
alert(v.age);
return false; // stops the loop
}
});
回答by Ali
You could use Jsel - https://github.com/dragonworx/jsel(for full disclosure, I am the owner of this library).
你可以使用 Jsel - https://github.com/dragonworx/jsel(为了完全披露,我是这个库的所有者)。
It uses a real XPath engine and is highly customizable. Runs in both Node.js and the browser.
它使用真正的 XPath 引擎并且是高度可定制的。在 Node.js 和浏览器中运行。
Given your original question, you'd find the people by name 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 you were always working with the same JSON schema you could create your own schema with jsel, and be able to use shorter expressions like:
如果您始终使用相同的 JSON 模式,则可以使用 jsel 创建自己的模式,并能够使用更短的表达式,例如:
dom.select("//person[@name='Peter']")
回答by Dexxo
You can search on a json object array using $.grep() like this:
您可以使用 $.grep() 搜索 json 对象数组,如下所示:
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);
回答by DuckMaestro
Once you have the JSON loaded into a JavaScript object, it's no longer a jQuery problem but is now a JavaScript problem. In JavaScript you could for instance write a search such as:
一旦将 JSON 加载到 JavaScript 对象中,它就不再是 jQuery 问题,而是 JavaScript 问题。例如,在 JavaScript 中,您可以编写一个搜索,例如:
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 !
回答by Hakan Bilgin
You can use DefiantJS (http://defiantjs.com) which extends the global object JSON with the method "search". With which you can query XPath queries on JSON structures. Example:
您可以使用 DefiantJS ( http://defiantjs.com),它使用“搜索”方法扩展全局对象 JSON。您可以使用它查询 JSON 结构上的 XPath 查询。例子:
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/
这是一个工作小提琴;
http://jsfiddle.net/hbi99/NhL7p/
回答by Martin Schuhfu?
There are some js-libraries that could help you with it:
有一些 js 库可以帮助你:
- JSONPath (something like XPath for JSON-Structures) - http://goessner.net/articles/JsonPath/
- JSONQuery - https://github.com/JasonSmith/jsonquery
- JSONPath(类似于 JSON 结构的 XPath) - http://goessner.net/articles/JsonPath/
- JSONQuery - https://github.com/JasonSmith/jsonquery
You might also want to take a look at Lawnchair, which is a JSON-Document-Store which works in the browser and has all sorts of querying-mechanisms.
您可能还想看看Lawnchair,它是一个 JSON-Document-Store,可在浏览器中运行并具有各种查询机制。
回答by Hardik Sondagar
I have kind of similar condition plus my Search Query not limited to particular Object property ( like "John" Search query should be matched with first_name and also with last_name property ). After spending some hours I got this function from Google's Angularproject. They have taken care of every possible cases.
我有类似的条件,加上我的搜索查询不限于特定的对象属性(如“John”搜索查询应该与 first_name 和 last_name 属性匹配)。花了几个小时后,我从 Google 的Angular项目中获得了这个功能。他们已经处理了所有可能的情况。
/* 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;
}
};
回答by cindy
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;
}