当在复杂的JSON数组和散列中搜索项时,比如:
[
{ "id": 1, "name": "One", "objects": [
{ "id": 1, "name": "Response 1", "objects": [
// etc.
}]
}
]
是否有某种查询语言,我可以用来在[0]中找到一个项目。id = 3的对象?
当在复杂的JSON数组和散列中搜索项时,比如:
[
{ "id": 1, "name": "One", "objects": [
{ "id": 1, "name": "Response 1", "objects": [
// etc.
}]
}
]
是否有某种查询语言,我可以用来在[0]中找到一个项目。id = 3的对象?
当前回答
是的,它叫做JSONPath:
它还集成到DOJO中。
其他回答
最新的XPath规范包括JSON支持:
XPath的主要目的是处理XML树和JSON树的节点。XPath得名于它使用路径符号在XML文档的层次结构中导航。XPath使用紧凑的非XML语法,以方便在uri和XML属性值中使用XPath。XPath 3.1为导航JSON树添加了类似的语法。
XQuery也是如此:
JSON是一种轻量级的数据交换格式,广泛用于在web上交换数据和在数据库中存储数据。许多应用程序将JSON与XML和HTML一起使用。XQuery 3.1扩展了XQuery以支持JSON和XML,向数据模型添加了映射和数组,并使用语言中的新表达式和[XQuery and XPath functions and Operators 3.1]中的新函数来支持它们。
XQuery可用于查询JSON,前提是处理器提供JSON支持。这是一个简单的例子,如何使用BaseX来查找“id”= 1的对象:
json:parse('[
{ "id": 1, "name": "One", "objects": [
{ "id": 1, "name": "Response 1", "objects": [ "etc." ] }
]}
]')//value[.//id = 1]
Json指针似乎也得到了越来越多的支持。
JMESPath是一个非常成熟的库,具有详细的规范和对多种语言的支持。
语法的例子:
// Select a single item
people[1].firstName
// Select a slice of an array
people[0:5]
// Select all the first names
people[*].firstName
// Select all first names based on search term
people[?state=='VA'].firstName
// Count how many people are over 35
length(people[?age>`35`])
// Select only the name and age of people over 35
people[?age>`35`].{name: name, age: age}
// Join expressions together to sort and join elements into a string
people[?state == 'WA'].name | sort(@) | join(', ', @)
在文档中还有更多的实例可以使用。
JS库精简了19kb,因此可能比某些库大,但考虑到广泛的特性,您可能会发现它值得。
其他选项
还有一些用于遍历/过滤JSON数据的其他选项,以及一些语法示例,以帮助您进行比较…
JSPath .automobiles{。maker ===“本田”&& .year > 2009}.model json:select()(更多的灵感来自CSS选择器) .automobile .maker:val("Honda") .model JSONPath(更多地受XPath启发) 美元.automobiles [? (@.maker =“本田”)]得
js看起来也很酷,这里有一个简单的例子:
var obj = {
"car": [
{"id": 10, "color": "silver", "name": "Volvo"},
{"id": 11, "color": "red", "name": "Saab"},
{"id": 12, "color": "red", "name": "Peugeot"},
{"id": 13, "color": "yellow", "name": "Porsche"}
],
"bike": [
{"id": 20, "color": "black", "name": "Cannondale"},
{"id": 21, "color": "red", "name": "Shimano"}
]
},
search = JSON.search(obj, '//car[color="yellow"]/name');
console.log( search );
// ["Porsche"]
var reds = JSON.search(obj, '//*[color="red"]');
for (var i=0; i<reds.length; i++) {
console.log( reds[i].name );
}
// Saab
// Peugeot
// Shimano