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

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

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


当前回答

如果您像我一样,只想进行基于路径的查找,但不关心真正的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'

其他回答

是的,它叫做JSONPath:

它还集成到DOJO中。

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 =“本田”)]得

我认为JSONQuery是JSONPath的超集,因此在dojo中取代了JSONPath。还有RQL。

来自Dojo文档:

JSONQuery是JSONPath的扩展版本,具有其他特性 为安全性、易用性和全面的数据查询集 工具包括过滤,递归搜索,排序,映射,范围 选择,以及具有通配符字符串比较的灵活表达式 以及各种运算符。

JSONselect对这个问题有另一种观点(类似CSS选择器,而不是XPath),并有一个JavaScript实现。

为了增加更多的选择,还有XPath。XPath 3.1处理JSON和XML。在XPath 3.1中,您需要的查询是?0?Objects?*[?id = 3)