JsonPath的用法

JsonPath的用法

今天有个临时需求,需要将很多json数据添加一个key value。
当听到这个需求,第一眼想到的便是fastjson,构造一堆list,map什么的,感觉特复杂。想着想着突然脑海里飘过XPath,然鹅XPath是基于xml,就百度一下看看有没有json path。居然还真有个JsonPath。。。突然发现自己很孤陋寡闻。
既然有了,那就学习一下,下面就说说今天的使用心得。

一、项目地址

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

二、在线测试

看网址像是官方的,可以在线测试表达式,还是蛮好使的
http://jsonpath.com/

三、文档

https://goessner.net/

gradle依赖

// https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path
compile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.4.0'

操作符

XPathJSONPathDescription
/$the root object/element
.@the current object/element
/. or []child operator
..n/aparent operator
//..recursive descent. JSONPath borrows this syntax from E4X.
**wildcard. All objects/elements regardless their names.
@n/aattribute access. JSON structures don’t have attributes.
[][]subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
|[,]Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
n/a[start: end:step]array slice operator borrowed from ES4.
[]?()applies a filter (script) expression.
n/a()script expression, using the underlying script engine.
()n/agrouping in Xpath

运算符

XPathJSONPathDescription
/store/book/author$.store.book[*].authorthe authors of all books in the store
//author$..authorall authors
/store/*$.store.*all things in store, which are some books and a red bicycle.
/store//price$.store..pricethe price of everything in the store.
//book[3]$..book[2]the third book
//book[last()]$…book[(@.length-1)]
$…book[-1:]
the last book in order.
//book[position() < 3]$…book[0,1]
$…book[:2]
the first two books
//book[isbn]$..book[?(@.isbn)]filter all books with isbn number
//book[price<10]$…book[?(@.price<10)]filter all books cheapier than 10
//*$..*all Elements in XML document. All members of JSON structure.

四、用例

使用JsonPath修改Json数据

{
    "apis":[
        {
            "ctime":"2018-11-08 16:01:16",
            "mtime":"2019-02-20 22:11:42",
            "modifierId":1,
            "creatorId":1,
            "apiId":"1",
            "authType":"none",
            "version":"v3",
            "path": "/test",
            "httpMethod":"POST",
            "serviceCode":"resource",
            "cateCode":"server-task",
            "mappingProtocol":"DUBBO",
            "modifyVersion":1,
            "onlineVersion":1,
            "isOnline":"Y",
            "isCached":"N",
            "cachedTime":10000,
            "requestMode":"MAPPING",
            "servCreatorId":1134,
            "requestMappingParam":{
                "requestParams":[
                    {
                        "name":"tenantId",
                        "type":"Long",
                        "paramLocation":"Query",
                        "isRequired":true,
                        "defaultValue":""
                    },
                    {
                        "name":"userId",
                        "type":"Long",
                        "paramLocation":"Query",
                        "isRequired":true,
                        "defaultValue":""
                    },
                    {
                        "name":"taskId",
                        "type":"Long",
                        "paramLocation":"Query",
                        "isRequired":false,
                        "description":"ID"
                    },
                    {
                        "name":"taskName",
                        "type":"String",
                        "paramLocation":"Query",
                        "isRequired":true,
                        "defaultValue":"",
                        "description":"名称"
                    }
                ]
            }
            "dubboParamMappings": {
                "leafParamMappings": [
                    {
                        "paramName":"tenantId",
                        "paramType":"java.lang.Long",
                        "paramMapping":"tenantId"
            	    }
                ]
            }
        }
    ]
}

apis是个列表,列表包含很多map集合。
每个map代表一个api,api中包含requestParams。
其中需要将requestParams中tenantId和userId参数加上headerMapping。

"requestParams":[
{
    "name":"tenantId",
    "type":"Long",
    "paramLocation":"Query",
    "isRequired":true,
    "defaultValue":"",
    "headerMapping":"X-Access-TenantId" // 需要添加的东西
},
{
    "name":"userId",
    "type":"Long",
    "paramLocation":"Query",
    "isRequired":true,
    "defaultValue":"",
    "headerMapping":"X-Access-UserId" // 需要添加的东西
},

首先,读取json文件:

InputStream inputStream = Files.newInputStream(Paths.get("/Users/admin/Downloads/resource.json"));

构造整个文档

DocumentContext document = JsonPath.parse(inputStream);

在指定位置添加key value

  1. $.apis[*]是获取所有apis,这里其实只有一个。。。
  2. $.apis[*].requestMappingParam是获取apis列表中每个map的requestMappingParam
  3. $.apis[*].requestMappingParam.requestParams是获取上一步requestMappingParam中的requestParams
  4. [?(@.name==“tenantId”&&!@.headerMapping)]这个是过滤条件,指的是requestParams中包含name且等于tenantId并且requestParams没有headerMapping这个key
document.put("$.apis[*].requestMappingParam.requestParams[?(@.name==\"tenantId\"&&!@.headerMapping)]", "headerMapping", "X-Access-TenantId");
document.put("$.apis[*].requestMappingParam.requestParams[?(@.name==\"userId\"&&!@.headerMapping)]", "headerMapping", "X-Access-UserId");
  1. 后面两个参数分别是key和value

写入修改后的json

Files.write(Paths.get("/tmp/resource.json")), context.jsonString().getBytes());

没几行代码便完成了

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JsonPath是一种用于解析和查询JSON文档的语法。它类似于XPath对XML文档的解析。通过使用JsonPath,您可以方便地查找节点并获取所需的数据。JsonPath语法包括以下几个部分: 1. 点操作符(.):用于访问对象的属性。例如,`$.store.book`表示访问JSON文档中的`store`对象的`book`属性。 2. 方括号操作符(\[\]):用于访问数组元素或过滤器。例如,`$.store.book\[0\]`表示访问数组`book`的第一个元素。 3. 通配符(*):用于匹配任意属性或数组元素。例如,`$.store.book\[*\].title`表示获取所有`book`数组中的`title`属性。 4. 过滤器(?()):用于根据条件过滤数组元素。例如,`$.store.book\[?(@.price < 10)\]`表示获取`price`小于10的所有`book`数组元素。 5. 逻辑运算符(&&、||):用于组合多个过滤器表达式。例如,`$.store.book\[?(@.price < 10 && @.category == 'fiction')\]`表示获取`price`小于10且`category`为'fiction'的所有`book`数组元素。 通过组合这些语法元素,您可以根据需要灵活地查询和过滤JSON文档中的数据。\[1\]\[2\] #### 引用[.reference_title] - *1* *2* [JsonPath完全介绍及详细使用教程](https://blog.csdn.net/qq_36595013/article/details/109455924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值