当在复杂的JSON数组和散列中搜索项时,比如:

[
    { "id": 1, "name": "One", "objects": [
        { "id": 1, "name": "Response 1", "objects": [
            // etc.
        }]
    }
]

是否有某种查询语言,我可以用来在[0]中找到一个项目。id = 3的对象?


当前回答

JMESPath现在似乎非常流行(截至2020年),并解决了JSONPath的许多问题。它适用于许多语言。

其他回答

如果您像我一样,只想进行基于路径的查找,但不关心真正的XPath,那么lodash的_.get()可以工作。来自lodash docs的例子:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// → 3

_.get(object, ['a', '0', 'b', 'c']);
// → 3

_.get(object, 'a.b.c', 'default');
// → 'default'

我知道的其他选择是

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.

最新的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指针似乎也得到了越来越多的支持。