当在复杂的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中。
其他回答
我知道的其他选择是
JSONiq specification, which specifies two subtypes of languages: one that hides XML details and provides JS-like syntax, and one that enriches XQuery syntax with JSON constructors and such. Zorba implements JSONiq. Corona, which builds on top of MarkLogic provides a REST interface for storing, managing, and searching XML, JSON, Text and Binary content. MarkLogic 6 and later provide a similar REST interface as Corona out of the box. MarkLogic 8 and later support JSON natively in both their XQuery and Server-side JavaScript environment. You can apply XPath on it.
HTH.
JMESPath现在似乎非常流行(截至2020年),并解决了JSONPath的许多问题。它适用于许多语言。
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 =“本田”)]得
@Naftule -使用" defy .js",可以用XPath表达式查询JSON结构。看看这个计算器,了解它是如何工作的:
http://www.defiantjs.com/#xpath_evaluator
与JSONPath不同,“defy .js”提供了对查询语法的全面支持——对JSON结构上的XPath。
defy .js的源代码可以在这里找到: https://github.com/hbi99/defiant.js
Jsel很棒,它基于真正的XPath引擎。它允许您创建XPath表达式来查找任何类型的JavaScript数据,而不仅仅是对象(字符串)。
您可以创建自定义模式和映射,从而完全控制XPath引擎如何处理数据。模式是一种定义如何在数据中定义元素、子元素、属性和节点值的方法。然后你可以创建自己的表达式来适应。
假设你有一个名为data的变量,其中包含来自问题的JSON,你可以使用jsel写:
jsel(data).select("//*[@id=3]")
这将返回id属性为3的任何节点。属性是对象内的任何基本元素(字符串、数字、日期、正则表达式)值。