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

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

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


当前回答

我知道OP用javascript标记了这个问题,但在我的情况下,我看起来完全一样,但从Java后端(与Camel)。

有趣的是,如果您使用的是像Camel这样的集成框架,jsonPath也由特定的Camel组件支持,从Camel 2.13开始。

例子来自上面的Camel文档:

from("queue:books.new")
  .choice()
    .when().jsonpath("$.store.book[?(@.price < 10)]")
      .to("jms:queue:book.cheap")
    .when().jsonpath("$.store.book[?(@.price < 30)]")
      .to("jms:queue:book.average")
    .otherwise()
      .to("jms:queue:book.expensive")

使用起来很简单。

其他回答

是的,它叫做JSONPath:

它还集成到DOJO中。

我知道OP用javascript标记了这个问题,但在我的情况下,我看起来完全一样,但从Java后端(与Camel)。

有趣的是,如果您使用的是像Camel这样的集成框架,jsonPath也由特定的Camel组件支持,从Camel 2.13开始。

例子来自上面的Camel文档:

from("queue:books.new")
  .choice()
    .when().jsonpath("$.store.book[?(@.price < 10)]")
      .to("jms:queue:book.cheap")
    .when().jsonpath("$.store.book[?(@.price < 30)]")
      .to("jms:queue:book.average")
    .otherwise()
      .to("jms:queue:book.expensive")

使用起来很简单。

Json指针似乎也得到了越来越多的支持。

@Naftule -使用" defy .js",可以用XPath表达式查询JSON结构。看看这个计算器,了解它是如何工作的:

http://www.defiantjs.com/#xpath_evaluator

与JSONPath不同,“defy .js”提供了对查询语法的全面支持——对JSON结构上的XPath。

defy .js的源代码可以在这里找到: https://github.com/hbi99/defiant.js

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