json - 从 JSONPath 中的过滤器表达式中选择第 N 个项目

标签 json jsonpath

我一直在尝试使用 JSONPath 过滤 JSON 中的特定元素,然后仅选择返回的结果数组中的第一个项目。

我的 baisc JSONPath 看起来像这样:

$.store.book[?(@.category==fiction)].price

我想加这个[0]像这样过滤:
$.store.book[?(@.category==fiction)][0].price

但它不返回结果或者如果我把 [0]在最后一个“价格”之后,我收到此错误:

Filter: [0]['price'] can only be applied to arrays



我一直在搜索,但找不到正确的语法来在应用过滤器后提取数组中的第一个元素,就像在 xpath 中一样。

这是我正在处理的基本 JSON:
{ "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
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

最佳答案

目前唯一的解决办法是:

List<Double> prices = JsonPath
   .parse(json)
   .read("$.store.book[?(@.category == 'fiction')].price");

Double firstPrice = prices.isEmpty() ? null : prices.get(0);

关于json - 从 JSONPath 中的过滤器表达式中选择第 N 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30322086/

相关文章:

javascript - 在 Python 2.7 中使用 json.loads 返回 unicode 对象而不是 dict

ROBOT 中的 Json 处理

json - 如何在 jsonpath 中转义特殊字符冒号 (':' )

json - JSONPath 中的 OR 运算符?

xml - 无法使用 json-eval 在 WSO2 ESB 配置中应用 concat 函数

javascript - 这个函数如何知道正在传递哪个属性?

Javascript变量范围问题

ios - UIPickerView 无法显示 JSON 数组数据

javascript - 使用 CSS 突出显示 JSONPath 中选定的文本

json - 有没有办法在JSONPath中获取字符串值的子字符串?