JsonPath教程

2024-06-11 06:48
文章标签 教程 jsonpath

本文主要是介绍JsonPath教程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 介绍

类似于XPath在xml文档中的定位,JsonPath表达式通常是用来路径检索或设置Json的。其表达式可以接受“dot–notation”和“bracket–notation”格式,例如$.store.book[0].title、$[‘store’][‘book’][0][‘title’]

2. 操作符

符号描述
$查询的根节点对象,用于表示一个json数据,可以是数组或对象
@过滤器断言(filter predicate)处理的当前节点对象,类似于java中的this字段
*通配符,可以表示一个名字或数字
..可以理解为递归搜索,Deep scan. Available anywhere a name is required.
.<name>表示一个子节点
[‘<name>’ (, ‘<name>’)]表示一个或多个子节点
[<number> (, <number>)]表示一个或多个数组下标
[start:end]数组片段,区间为[start,end),不包含end
[?(<expression>)]过滤器表达式,表达式结果必须是boolean

3. 函数

可以在JsonPath表达式执行后进行调用,其输入值为表达式的结果。

名称描述输出
min()获取数值类型数组的最小值Double
max()获取数值类型数组的最大值Double
avg()获取数值类型数组的平均值Double
stddev()获取数值类型数组的标准差Double
length()获取数值类型数组的长度Integer

4. 过滤器

过滤器是用于过滤数组的逻辑表达式,一个通常的表达式形如:[?(@.age > 18)],可以通过逻辑表达式&&或||组合多个过滤器表达式,例如[?(@.price < 10 && @.category == ‘fiction’)],字符串必须用单引号或双引号包围,例如[?(@.color == ‘blue’)] or [?(@.color == “blue”)]。

操作符描述
==等于符号,但数字1不等于字符1(note that 1 is not equal to ‘1’)
!=不等于符号
<小于符号
<=小于等于符号
>大于符号
>=大于等于符号
=~判断是否符合正则表达式,例如[?(@.name =~ /foo.*?/i)]
in所属符号,例如[?(@.size in [‘S’, ‘M’])]
nin排除符号
sizesize of left (array or string) should match right
empty判空符号

5. 示例

{"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}},"expensive": 10
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
JsonPath表达式结果
$.store.book[*].author

$..author
[
“Nigel Rees”,
“Evelyn Waugh”,
“Herman Melville”,
“J. R. R. Tolkien”
]
$.store.* 显示所有叶子节点值[
[
{
”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
}
],
{
”color” : “red”,
”price” : 19.95
}
]
$.store..price[
8.95,
12.99,
8.99,
22.99,
19.95
]
$..book[0,1]

$..book[:2]
[
{
”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
}
]
$..book[-2:]获取最后两本书
$..book[2:][
{
”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
}
]
$..book[?(@.isbn)]所有具有isbn属性的书
$.store.book[?(@.price < 10)]所有价格小于10的书
$..book[?(@.price <= $[‘expensive’])]所有价格低于expensive字段的书
$..book[?(@.author =~ /.*REES/i)]所有符合正则表达式的书
[
{
”category” : “reference”,
”author” : “Nigel Rees”,
”title” : “Sayings of the Century”,
”price” : 8.95
}
]
$..*返回所有
$..book.length()[
4
]

测试请点击http://jsonpath.herokuapp.com/?path=$.store.book[*].author

6. 常见用法

通常是直接使用静态方法API进行调用,例如:

String json = "...";List<String> authors = JsonPath.read(json, "$.store.book[*].author");
  • 1
  • 2
  • 3

但以上方式仅仅适用于解析一次json的情况,如果需要对同一个json解析多次,不建议使用,因为每次read都会重新解析一次json,针对此种情况,建议使用ReadContext、WriteContext,例如:

String json = "...";ReadContext ctx = JsonPath.parse(json);List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");List<Map<String, Object>> expensiveBooks = JsonPath.using(configuration).parse(json).read("$.store.book[?(@.price > 10)]", List.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

7. 返回值是什么?

通常read后的返回值会进行自动转型到指定的类型,对应明确定义definite的表达式,应指定其对应的类型,对于indefinite含糊表达式,例如包括..、?(<expression>)、[<number>, <number> (, <number>)],通常应该使用数组。如果需要转换成具体的类型,则需要通过configuration配置mappingprovider,如下:

String json = "{\"date_as_long\" : 1411455611975}";
//使用JsonSmartMappingProvider
Date date = JsonPath.parse(json).read("$['date_as_long']", Date.class);
//使用GsonMappingProvider
Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);
  • 1
  • 2
  • 3
  • 4
  • 5

8. MappingProvider SPI反序列化器

这里写图片描述

其中JsonSmartMappingProvider提供了如下基本数据类型的转换,此provider是默认设置的,在Configuration.defaultConfiguration()中返回的DefaultsImpl类,使用的就是JsonSmartMappingProvider。

DEFAULT.registerReader(Long.class, new LongReader());
DEFAULT.registerReader(long.class, new LongReader());
DEFAULT.registerReader(Integer.class, new IntegerReader());
DEFAULT.registerReader(int.class, new IntegerReader());
DEFAULT.registerReader(Double.class, new DoubleReader());
DEFAULT.registerReader(double.class, new DoubleReader());
DEFAULT.registerReader(Float.class, new FloatReader());
DEFAULT.registerReader(float.class, new FloatReader());
DEFAULT.registerReader(BigDecimal.class, new BigDecimalReader());
DEFAULT.registerReader(String.class, new StringReader());
DEFAULT.registerReader(Date.class, new DateReader());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

切换Provider,如下:

Configuration.setDefaults(new Configuration.Defaults() {private final JsonProvider jsonProvider = new JacksonJsonProvider();private final MappingProvider mappingProvider = new JacksonMappingProvider();@Overridepublic JsonProvider jsonProvider() {return jsonProvider;}@Overridepublic MappingProvider mappingProvider() {return mappingProvider;}@Overridepublic Set<Option> options() {return EnumSet.noneOf(Option.class);}
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

9. Predicates过滤器断言

有三种方式创建过滤器断言。

9.1 Inline Predicates

即使用过滤器断言表达式?(<@expression>),例如:

List<Map<String, Object>> books =  JsonPath.parse(json).read("$.store.book[?(@.price < 10)]");
  • 1
  • 2

9.2 Filter Predicates

使用Filter API。例如:

import static com.jayway.jsonpath.JsonPath.parse;
import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
...
...Filter cheapFictionFilter = filter(where("category").is("fiction").and("price").lte(10D)
);List<Map<String, Object>> books =  parse(json).read("$.store.book[?]", cheapFictionFilter);Filter fooOrBar = filter(where("foo").exists(true)).or(where("bar").exists(true)
);Filter fooAndBar = filter(where("foo").exists(true)).and(where("bar").exists(true)
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

注意:

  • JsonPath表达式中必须要有断言占位符?,当有多个占位符时,会依据顺序进行替换。
  • 多个filter之间还可以使用or或and。

9.3 Roll Your Own

自己实现Predicate接口。

Predicate booksWithISBN = new Predicate() {@Overridepublic boolean apply(PredicateContext ctx) {return ctx.item(Map.class).containsKey("isbn");}
};List<Map<String, Object>> books = reader.read("$.store.book[?].isbn", List.class, booksWithISBN);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

10. 返回检索到的Path路径列表

有时候需要返回当前JsonPath表达式所检索到的全部路径,可以如下使用:

Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build();List<String> pathList = using(conf).parse(json).read("$..author");assertThat(pathList).containsExactly("$['store']['book'][0]['author']","$['store']['book'][1]['author']","$['store']['book'][2]['author']","$['store']['book'][3]['author']");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

11. 配置Options

11.1 DEFAULT_PATH_LEAF_TO_NULL

当检索不到时返回null对象,否则如果不配置这个,会直接抛出异常PathNotFoundException,例如:

[{"name" : "john","gender" : "male"},{"name" : "ben"}
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
Configuration conf = Configuration.defaultConfiguration();//Works fine
String gender0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
//PathNotFoundException thrown
String gender1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");Configuration conf2 = conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);//Works fine
String gender0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
//Works fine (null is returned)
String gender1 = JsonPath.using(conf2).parse(json).read("$[1]['gender']");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

11.2 ALWAYS_RETURN_LIST

总是返回list,即便是一个确定的非list类型,也会被包装成list。

11.3 SUPPRESS_EXCEPTIONS

不抛出异常,需要判断如下:

  • ALWAYS_RETURN_LIST开启,则返回空list
  • ALWAYS_RETURN_LIST关闭,则返回null

11.4 AS_PATH_LIST

返回path

11.5 REQUIRE_PROPERTIES

如果设置,则不允许使用通配符,比如$[*].b,会抛出PathNotFoundException异常。

12. Cache SPI

每次read时都会获取cache,以提高速度,但默认情况下是不启用的。

@Override
public <T> T read(String path, Predicate... filters) {notEmpty(path, "path can not be null or empty");Cache cache = CacheProvider.getCache();path = path.trim();LinkedList filterStack = new LinkedList<Predicate>(asList(filters));String cacheKey = Utils.concat(path, filterStack.toString());JsonPath jsonPath = cache.get(cacheKey);if(jsonPath != null){return read(jsonPath);} else {jsonPath = compile(path, filters);cache.put(cacheKey, jsonPath);return read(jsonPath);}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

JsonPath 2.1.0提供新的spi,必须在使用前或抛出JsonPathException前配置。目前提供了两种实现:

  • com.jayway.jsonpath.spi.cache.NOOPCache (no cache)
  • com.jayway.jsonpath.spi.cache.LRUCache (default, thread safe)

如果想要自己实现,例如:

CacheProvider.setCache(new Cache() {//Not thread safe simple cacheprivate Map<String, JsonPath> map = new HashMap<String, JsonPath>();@Overridepublic JsonPath get(String key) {return map.get(key);}@Overridepublic void put(String key, JsonPath jsonPath) {map.put(key, jsonPath);}
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

参考:

https://github.com/jayway/JsonPath JsonPath

这篇关于JsonPath教程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1050439

相关文章

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

SWAP作物生长模型安装教程、数据制备、敏感性分析、气候变化影响、R模型敏感性分析与贝叶斯优化、Fortran源代码分析、气候数据降尺度与变化影响分析

查看原文>>>全流程SWAP农业模型数据制备、敏感性分析及气候变化影响实践技术应用 SWAP模型是由荷兰瓦赫宁根大学开发的先进农作物模型,它综合考虑了土壤-水分-大气以及植被间的相互作用;是一种描述作物生长过程的一种机理性作物生长模型。它不但运用Richard方程,使其能够精确的模拟土壤中水分的运动,而且耦合了WOFOST作物模型使作物的生长描述更为科学。 本文让更多的科研人员和农业工作者

沁恒CH32在MounRiver Studio上环境配置以及使用详细教程

目录 1.  RISC-V简介 2.  CPU架构现状 3.  MounRiver Studio软件下载 4.  MounRiver Studio软件安装 5.  MounRiver Studio软件介绍 6.  创建工程 7.  编译代码 1.  RISC-V简介         RISC就是精简指令集计算机(Reduced Instruction SetCom

前端技术(七)——less 教程

一、less简介 1. less是什么? less是一种动态样式语言,属于css预处理器的范畴,它扩展了CSS语言,增加了变量、Mixin、函数等特性,使CSS 更易维护和扩展LESS 既可以在 客户端 上运行 ,也可以借助Node.js在服务端运行。 less的中文官网:https://lesscss.cn/ 2. less编译工具 koala 官网 http://koala-app.

【Shiro】Shiro 的学习教程(三)之 SpringBoot 集成 Shiro

目录 1、环境准备2、引入 Shiro3、实现认证、退出3.1、使用死数据实现3.2、引入数据库,添加注册功能后端代码前端代码 3.3、MD5、Salt 的认证流程 4.、实现授权4.1、基于角色授权4.2、基于资源授权 5、引入缓存5.1、EhCache 实现缓存5.2、集成 Redis 实现 Shiro 缓存 1、环境准备 新建一个 SpringBoot 工程,引入依赖:

Windows环境利用VS2022编译 libvpx 源码教程

libvpx libvpx 是一个开源的视频编码库,由 WebM 项目开发和维护,专门用于 VP8 和 VP9 视频编码格式的编解码处理。它支持高质量的视频压缩,广泛应用于视频会议、在线教育、视频直播服务等多种场景中。libvpx 的特点包括跨平台兼容性、硬件加速支持以及灵活的接口设计,使其可以轻松集成到各种应用程序中。 libvpx 的安装和配置过程相对简单,用户可以从官方网站下载源代码

PHP APC缓存函数使用教程

APC,全称是Alternative PHP Cache,官方翻译叫”可选PHP缓存”。它为我们提供了缓存和优化PHP的中间代码的框架。 APC的缓存分两部分:系统缓存和用户数据缓存。(Linux APC扩展安装) 系统缓存 它是指APC把PHP文件源码的编译结果缓存起来,然后在每次调用时先对比时间标记。如果未过期,则使用缓存的中间代码运行。默认缓存 3600s(一小时)。但是这样仍会浪费大量C

Qt多语种开发教程

Qt作为跨平台的开发工具,早已应用到各行各业的软件开发中。 今天讲讲,Qt开发的正序怎么做多语言开发。就是说,你设置中文,就中文显示;设置英语就英文显示,设置繁体就繁体显示,设置发育就显示法语等。 开发环境(其实多语种这块根环境没太大关系):win10,Qt.5.12.10 一.先用QtCreator创建一个简单的桌面程序 1.工程就随便命名“LanguageTest”,其他默认。 2.在设计师

如何打造个性化大学生线上聊天交友系统?Java SpringBoot Vue教程,2025最新设计思路

✍✍计算机编程指导师 ⭐⭐个人介绍:自己非常喜欢研究技术问题!专业做Java、Python、微信小程序、安卓、大数据、爬虫、Golang、大屏等实战项目。 ⛽⛽实战项目:有源码或者技术上的问题欢迎在评论区一起讨论交流! ⚡⚡ Java实战 | SpringBoot/SSM Python实战项目 | Django 微信小程序/安卓实战项目 大数据实战项目 ⚡⚡文末获取源码 文章目录