【问题标题】:how to compare each element in array?如何比较数组中的每个元素?
【发布时间】:2021-06-22 09:18:26
【问题描述】:
{
  "store": {
    "book": [
      {
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      {
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ]
  }
}

以下是我的情况: author=='Nigel Rees'.price

我的查询表达式:$.store.book[?($.store.book[?(@.author == 'Nigel Rees')].price < $.store.book[?(@.author == 'Evelyn Waugh')].price)]

我希望它会返回以下结果:

{
    "category": "reference",
    "author": "Nigel Rees",
    "title": "Sayings of the Century",
    "price": 8.95
}

正确的表达方式是什么?

【问题讨论】:

    标签: java jsonpath


    【解决方案1】:

    通常,要遍历数组中的项目并执行比较,您需要使用过滤器选择器:

    $.store.books[?(@.price<12.99)]
    

    但这不允许您将项目相互比较。在该表达式中,您应该(可能取决于您正在使用的库)能够使用 $ 来引用 JSON 根。这将允许您与特定项目进行比较:

    $.store.books[?(@.price<$.store.books[1].price)]
    

    这会将所有图书价格与数组中第二本书的价格进行比较。我认为这是您使用 JSON 路径最接近的方法。


    我们目前正在处理specification for JSON Path 来定义官方语法和功能集。随意打开一个问题(并链接到此问题)以请求“多迭代器”支持,以便可以相互比较项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      • 2017-10-30
      • 2017-12-25
      • 2019-12-10
      • 1970-01-01
      相关资源
      最近更新 更多