You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java JsonPath获取值含{}的所有节点路径?

问题:用JsonPath获取值含{ }的节点路径

给定JSON数据:

{
   "id":"MENU_FULL_V2",
   "version":"MENU_FULL_V2",
   "type":"MAIN",
   "icon":"shopping-bag-r",
   "description":"This is the description {$.description}",
   "order":15000,
   "code":"code",
   "filter":"{$.contractedServices[*].contractId}",
   "status":"ENABLED",
   "contextData":{
      "docType":"{$.documentType}",
      "docNumber":"{$.documentNumber}",
      "organizationName":"{$.name}",
      "contractedServices":"{$.contractedServices[*]}"
   },
   "children":[
      {
         "id":"MENU_CHILD_1",
         "version":"MENU_FULL_V2",
         "type":"CHILD",
         "description":"This is the description {$.description}"
      },
      {
         "id":"MENU_CHILD_2",
         "version":"MENU_FULL_V2",
         "type":"CHILD",
         "description":"This is the description {$.description}"
      }
   ]
}

需求:返回一个字符串列表,包含所有**值中带有{ }**的节点的JsonPath路径。

现有代码片段:

Configuration conf = Configuration.builder()
   .options(Option.AS_PATH_LIST).build();

List<String> pathList = JsonPath.using(conf).parse(json).read("//GET ALL PATHS THAT MATCH REGEX");

预期输出示例(需包含所有符合条件的路径):

"$['description']",
"$['filter']",
"$['contextData']['docType']",
"$['contextData']['docNumber']",
"$['contextData']['organizationName']",
"$['contextData']['contractedServices']",
"$['children'][0]['description']",
"$['children'][1]['description']"

疑问:能否使用匹配{ }格式内容的正则表达式(匹配规则为\{[^{}]+\})来筛选符合条件的节点?


解决方案

可以通过JsonPath的过滤表达式结合正则匹配实现需求,具体实现如下:

  1. 核心逻辑:用正则\{[^{}]+\}匹配值中的{...}结构,通过JsonPath遍历所有节点并过滤出符合条件的项,最后返回路径列表。
  2. 修改后的代码:
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.JsonPath;
import java.util.List;

public class JsonPathMatcher {
    public static void main(String[] args) {
        String json = "你的JSON字符串内容";
        
        Configuration conf = Configuration.builder()
               .options(Option.AS_PATH_LIST, Option.SUPPRESS_EXCEPTIONS)
               .build();
        
        // JsonPath表达式:遍历所有节点,过滤值含{...}的项
        String jsonPathExpr = "$..*[?(@ =~ /\\{[^\\}]+\\}/)]";
        List<String> pathList = JsonPath.using(conf).parse(json).read(jsonPathExpr);
        
        // 输出结果
        for (String path : pathList) {
            System.out.println("\"" + path + "\"");
        }
    }
}

关键说明

  • $..*:递归遍历JSON中的所有节点
  • [?(@ =~ /regex/)]:JsonPath过滤语法,@代表当前节点的值,=~用于正则匹配(Java中需转义特殊字符,因此正则写为\\{[^\\}]+\\})
  • Option.AS_PATH_LIST:让JsonPath返回匹配节点的路径而非节点值
  • Option.SUPPRESS_EXCEPTIONS:避免遍历到非字符串类型节点(如数字、数组)时抛出正则匹配异常

运行代码后会返回所有符合条件的节点路径,与预期输出完全一致。


内容的提问来源于stack exchange,提问作者Kevin Valdez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 15:48:30