JsonPath | FastJson的JSONPath使用

2024-06-09 17:08
文章标签 使用 fastjson jsonpath

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

一. 简介

JSONPath - 用于JSON的XPath

用来解析多层嵌套的json数据;JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具.

 JsonPath有许多编程语言,如Javascript、Python、PHP、Java等

JsonPath提供的json解析非常强大,它提供了类似正则表达式的语法,基本上可以满足所有你想要获得的json内容。

 JSONPath GitHub: https://github.com/json-path/JsonPath 

JsonPath表达式始终引用JSON结构,其方式与XPath表达式与XML文档结合使用的方式相同。$无论是对象还是数组,JsonPath中的“根成员对象”始终被称为。

JsonPath表达式可以使用点表示法

$.store.book[0].title

或括号表示法

$['store']['book'][0]['title']

 二、API

使用的时候建议缓存JSONPath对象,这样能够提高求值的性能。

package com.alibaba.fastjson;public class JSONPath {          //  求值,静态方法public static Object eval(Object rootObject, String path);// 计算Size,Map非空元素个数,对象非空元素个数,Collection的Size,数组的长度。其他无法求值返回-1public static int size(Object rootObject, String path);// 是否包含,path中是否存在对象public static boolean contains(Object rootObject, String path) { }// 是否包含,path中是否存在指定值,如果是集合或者数组,在集合中查找value是否存在public static boolean containsValue(Object rootObject, String path, Object value) { }// 修改制定路径的值,如果修改成功,返回true,否则返回falsepublic static boolean set(Object rootObject, String path, Object value) {}// 在数组或者集合中添加元素public static boolean array_add(Object rootObject, String path, Object... values);
}

三、支持语法

JSONPATH描述
</td><td>根对象,例如.name
[num]数组访问,其中num是数字,可以是负数。例如$[0].leader.departments[-1].name
[num0,num1,num2…]数组多个元素访问,其中num是数字,可以是负数,返回数组中的多个元素。例如$[0,3,-2,5]
[start:end]数组范围访问,其中start和end是开始小表和结束下标,可以是负数,返回数组中的多个元素。例如$[0:5]
[start:end :step]数组范围访问,其中start和end是开始小表和结束下标,可以是负数;step是步长,返回数组中的多个元素。例如$[0:5:2]
[?(key)]对象属性非空过滤,例如$.departs[?(name)]
[key > 123]数值类型对象属性比较过滤,例如$.departs[id >= 123],比较操作符支持=,!=,>,>=,<,<=
[key = ‘123’]字符串类型对象属性比较过滤,例如$.departs[name = ‘123’],比较操作符支持=,!=,>,>=,<,<=
[key like ‘aa%’]字符串类型like过滤,
例如$.departs[name like ‘sz*’],通配符只支持% 
支持not like
[key rlike ‘regexpr’]字符串类型正则匹配过滤,
例如departs[name like ‘aa(.)*’],
正则语法为jdk的正则语法,支持not rlike
[key in (‘v0’, ‘v1’)]IN过滤, 支持字符串和数值类型 
例如: 
.departs[namein(′wenshao′,′Yako′)]<br/>.departs[id not in (101,102)]
[key between 234 and 456]BETWEEN过滤, 支持数值类型,支持not between 
例如: 
.departs[idbetween101and201]<br/>.departs[id not between 101 and 201]
length() 或者 size()数组长度。例如$.values.size() 
支持类型java.util.Map和java.util.Collection和数组
.属性访问,例如$.name
..deepScan属性访问,例如$..name
*对象的所有属性,例如$.leader.*
[‘key’]属性访问。例如$[‘name’]
[‘key0’,’key1’]多个属性访问。例如$[‘id’,’name’]

以下两种写法的语义是相同的:

$.store.book[0].title

$['store']['book'][0]['title']

四、语法示例

JSONPath语义
$根对象
$[-1]最后元素
$[:-2]第1个至倒数第2个
$[1:]第2个之后所有元素
$[1,2,3]集合中1,2,3个元素

五、API示例

5.1 基础例子

public void test_entity() throws Exception {Entity entity = new Entity(123, new Object());Assert.assertSame(entity.getValue(), JSONPath.eval(entity, "$.value")); Assert.assertTrue(JSONPath.contains(entity, "$.value"));Assert.assertTrue(JSONPath.containsValue(entity, "$.id", 123));Assert.assertTrue(JSONPath.containsValue(entity, "$.value", entity.getValue())); Assert.assertEquals(2, JSONPath.size(entity, "$"));Assert.assertEquals(0, JSONPath.size(new Object[], "$")); 
}public static class Entity {private Integer id;private String name;private Object value;public Entity() {}public Entity(Integer id, Object value) { this.id = id; this.value = value; }public Entity(Integer id, String name) { this.id = id; this.name = name; }public Entity(String name) { this.name = name; }public Integer getId() { return id; }public Object getValue() { return value; }        public String getName() { return name; }public void setId(Integer id) { this.id = id; }public void setName(String name) { this.name = name; }public void setValue(Object value) { this.value = value; }
}

5.2 读取集合多个元素的某个属性

List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));List<String> names = (List<String>)JSONPath.eval(entities, "$.name"); // 返回enties的所有名称
Assert.assertSame(entities.get(0).getName(), names.get(0));
Assert.assertSame(entities.get(1).getName(), names.get(1));

5.3 返回集合中多个元素

List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
entities.add(new Entity("Yako"));List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[1,2]"); // 返回下标为1和2的元素
Assert.assertEquals(2, result.size());
Assert.assertSame(entities.get(1), result.get(0));
Assert.assertSame(entities.get(2), result.get(1));

 5.4 按范围返回集合的子集

List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
entities.add(new Entity("Yako"));List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[0:2]"); // 返回下标从0到2的元素
Assert.assertEquals(3, result.size());
Assert.assertSame(entities.get(0), result.get(0));
Assert.assertSame(entities.get(1), result.get(1));
Assert.assertSame(entities.get(2), result.get(1));

5.5 通过条件过滤,返回集合的子集

List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, "yakolee"));
entities.add(new Entity(1004, null));List<Object> result = (List<Object>) JSONPath.eval(entities, "[id in (1001)]");
Assert.assertEquals(1, result.size());
Assert.assertSame(entities.get(0), result.get(0));

5.6 根据属性值过滤条件判断是否返回对象,修改对象,数组属性添加元素

Entity entity = new Entity(1001, "ljw2083");
Assert.assertSame(entity , JSONPath.eval(entity, "[id = 1001]"));
Assert.assertNull(JSONPath.eval(entity, "[id = 1002]"));JSONPath.set(entity, "id", 123456); //将id字段修改为123456
Assert.assertEquals(123456, entity.getId().intValue());JSONPath.set(entity, "value", new int[0]); //将value字段赋值为长度为0的数组
JSONPath.arrayAdd(entity, "value", 1, 2, 3); //将value字段的数组添加元素1,2,3

5.7 具体用例测试


@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class JSONpathControllerTest {@Testpublic void test() {User user = new User("itguang", "123456", "123@qq.com");String username = (String) JSONPath.eval(user, "$.username");log.info("$.username = {}", username);Entity entity = new Entity(123, user);User user1 = (User) JSONPath.eval(entity, "$.value");log.info("user={}", user1.toString());}@Testpublic void test2() {User user = new User("itguang", "123456", "123@qq.com");Entity entity = new Entity(123, user);//判断entity中是否有 databoolean contains = JSONPath.contains(entity, "$.data");Assert.assertTrue(contains);//判断 entity.data.username 属性值是否为 itguangboolean containsValue = JSONPath.containsValue(entity, "$.data.username", "itguang");Assert.assertTrue(containsValue);Assert.assertEquals(2, JSONPath.size(entity, "$"));}@Testpublic void test3() {List<Entity> entities = new ArrayList<Entity>();entities.add(new Entity("逻辑"));entities.add(new Entity("叶文杰"));entities.add(new Entity("程心"));//返回集合中多个元素List<String> names = (List<String>) JSONPath.eval(entities, "$.name");log.info("返回集合中多个元素names={}", names);//返回下标 0 和 2 的元素List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[0,2]");log.info("返回下标 0 和 2 的元素={}", result);// 返回下标从0到2的元素List<Entity> result2 = (List<Entity>) JSONPath.eval(entities, "[0:2]");log.info("返回下标从0到2的元素={}", result2);}@Testpublic void test4() {List<Entity> entities = new ArrayList<Entity>();entities.add(new Entity(1001, "逻辑"));entities.add(new Entity(1002, "程心"));entities.add(new Entity(1003, "叶文杰"));entities.add(new Entity(1004, null));//通过条件过滤,返回集合的子集List<Entity> result = (List<Entity>) JSONPath.eval(entities, "[id in (1001)]");log.info("通过条件过滤,返回集合的子集={}", result);}/*** 使用JSONPrase 解析JSON字符串或者Object对象* <p>* read(String json, String path)//直接使用json字符串匹配* <p>* eval(Object rootObject, String path) //直接使用 对象匹配* <p>* <p>* {"store":{"bicycle":{"color":"red","price":19.95},"book":[{"author":"Nigel Rees","price":8.95,"category":"reference","title":"Sayings of the Century"},{"author":"Evelyn Waugh","price":12.99,"isbn":"0-553-21311-3","category":"fiction","title":"Sword of Honour"}]}}*/@Testpublic void test5() {String jsonStr = "{\n" +"    \"store\": {\n" +"        \"bicycle\": {\n" +"            \"color\": \"red\",\n" +"            \"price\": 19.95\n" +"        },\n" +"        \"book\": [\n" +"            {\n" +"                \"author\": \"刘慈欣\",\n" +"                \"price\": 8.95,\n" +"                \"category\": \"科幻\",\n" +"                \"title\": \"三体\"\n" +"            },\n" +"            {\n" +"                \"author\": \"itguang\",\n" +"                \"price\": 12.99,\n" +"                \"category\": \"编程语言\",\n" +"                \"title\": \"go语言实战\"\n" +"            }\n" +"        ]\n" +"    }\n" +"}";JSONObject jsonObject = JSON.parseObject(jsonStr);log.info(jsonObject.toString());//得到所有的书List<Book> books = (List<Book>) JSONPath.eval(jsonObject, "$.store.book");log.info("books={}", books);//得到所有的书名List<String> titles = (List<String>) JSONPath.eval(jsonObject, "$.store.book.title");log.info("titles={}", titles);//第一本书titleString title = (String) JSONPath.read(jsonStr, "$.store.book[0].title");log.info("title={}", title);//price大于10元的bookList<Book> list = (List<Book>) JSONPath.read(jsonStr, "$.store.book[price > 10]");log.info("price大于10元的book={}",list);//price大于10元的titleList<String> list2 =(List<String>) JSONPath.read(jsonStr, "$.store.book[price > 10].title");log.info("price大于10元的title={}",list2);//category(类别)为科幻的bookList<Book> list3 = (List<Book>) JSONPath.read(jsonStr,"$.store.book[category = '科幻']");log.info("category(类别)为科幻的book={}",list3);//bicycle的所有属性值Collection<String> values = (Collection<String>) JSONPath.eval(jsonObject, "$.store.bicycle.*");log.info("bicycle的所有属性值={}",values);//bicycle的color和price属性值List<String> read =(List<String>) JSONPath.read(jsonStr, "$.store.bicycle['color','price']");log.info("bicycle的color和price属性值={}",read);}}

源码地址: https://github.com/itguang/gitbook-smile/blob/master/springboot-fastjson/fastjson%E4%B9%8BJSONPath%E4%BD%BF%E7%94%A8.md

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



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

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

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

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

【北交大信息所AI-Max2】使用方法

BJTU信息所集群AI_MAX2使用方法 使用的前提是预约到相应的算力卡,拥有登录权限的账号密码,一般为导师组共用一个。 有浏览器、ssh工具就可以。 1.新建集群Terminal 浏览器登陆10.126.62.75 (如果是1集群把75改成66) 交互式开发 执行器选Terminal 密码随便设一个(需记住) 工作空间:私有数据、全部文件 加速器选GeForce_RTX_2080_Ti

【Linux 从基础到进阶】Ansible自动化运维工具使用

Ansible自动化运维工具使用 Ansible 是一款开源的自动化运维工具,采用无代理架构(agentless),基于 SSH 连接进行管理,具有简单易用、灵活强大、可扩展性高等特点。它广泛用于服务器管理、应用部署、配置管理等任务。本文将介绍 Ansible 的安装、基本使用方法及一些实际运维场景中的应用,旨在帮助运维人员快速上手并熟练运用 Ansible。 1. Ansible的核心概念