从JSONPath中的过滤器表达式中选择第N个项目 [英] Pick the Nth item from a filter expression in JSONPath

查看:460
本文介绍了从JSONPath中的过滤器表达式中选择第N个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been trying to filter a specific element in my JSON using JSONPath and then to choose only the 1st item in the returned array of results.

我的baisc JSONPath看起来像这样:

My baisc JSONPath looks something like this:

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

我想这样添加[0]过滤器:

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

,但是它不返回结果,或者如果我在最后一个价格"之后放置[0],则会出现此错误:

but it doesn't return results or if I put the [0] after the last "price" I get this error:

过滤器:[0] ['price']仅可应用于数组

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

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

I've been searching and couldn't find the right syntax to pull the 1st element in the array after applying a filter, just like in xpath.

这是我正在使用的基本JSON:

This is the base JSON I'm working on:

{ "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
    }
  }
}

推荐答案

当前唯一的解决方案是:

Currently the only solution is:

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

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

这篇关于从JSONPath中的过滤器表达式中选择第N个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆