首页 > 解决方案 > 如何比较数组中的每个元素?

问题描述

{
  "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 < author=='Evelyn Waugh'.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
}

正确的表达方式是什么?

标签: javajsonpath

解决方案


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

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

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

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

这会将所有书籍价格与数组中第二本书的价格进行比较。我认为这是您将使用 JSON Path 获得的最接近的结果。


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


推荐阅读