递归解析Json,实现生成可视化Tree+快速获取JsonPath

内部平台的一个小功能点的实现过程,分享给大家:

递归解析Json,可以实现生成可视化Tree+快速获取JsonPath

步骤:

1.利用JsonPath读取根,获取JsonObject

2.递归层次遍历JsonObjec,保存结点信息

3.利用zTree展示结点为可视化树,点击对应树的结点即可获取对应结点的JsonPath

1.利用JsonPath读取根,获取JsonObject

示例Json:

复制代码
{
  "errorMessage": null,
  "errorCode": null,
  "dates": {
    "tradeAmt": null,
    "riskLevel": "LEVEL30",
    "optSelected": {
      "77": [
        {
          "optionContent": "20-50万元",
          "productCode": null,
          "created": null,
          "optionOrder": null,
          "modified": null,
          "id": 361,
          "optionScore": 8,
          "isInvalid": 1
        }
      ],
      "78": [
        {
          "optionContent": "资产50-500万元,无债务或债务较轻",
          "productCode": null,
          "created": null,
          "optionOrder": null,
          "modified": null,
          "id": 365,
          "optionScore": 6,
          "isInvalid": 1
        }
      ]
    },
    "riskInfoResult": {
      "optLetter": "A",
      "mqOrder": "1",
      "residenceCountryCode": null,
      "taxReason": null,
      "residenceCountryName": null,
      "residenceCountryNameEn": null,
      "countryNameEn": null,
      "taxInfoCode": null,
      "taxInfoIsCompleted": true,
      "taxInfoIsRight": true,
      "countryCode": null,
      "taxId": null,
      "countryName": null,
      "taxReasonInt": null
    },
    "created": 1565654328000,
    "questions": [
      {
        "questionContent": "您的职业?",
        "productCode": null,
        "created": 1498630051000,
        "options": null,
        "questionSource": "BUSINESS",
        "modified": 1498630051000,
        "id": 75,
        "isInvalid": 1,
        "questionType": 1,
        "order": 1
      },
      {
        "questionContent": "您的主要收入来源是?",
        "productCode": null,
        "created": 1498630051000,
        "options": null,
        "questionSource": "BUSINESS",
        "modified": 1498630051000,
        "id": 76,
        "isInvalid": 1,
        "questionType": 1,
        "order": 2
      }
    ],
    "serialCode": "123",
    "isInvalid": 1,
    "expireTime": 1628783999000,
    "productCode": null,
    "modified": 1565654328000,
    "examScore": 56,
    "id": 4564568,
    "results": {
      "77": "361",
      "78": "365"
    },
    "account": "test"
  },
  "status": "SUCCESS"
}

Java代码:

复制代码
String jsonStr = "";
Object rootJson = JsonPath.read(jsonStr, "$");

2.递归层次遍历JsonObjec,保存结点信息

Java代码

复制代码
ZTreeNode zTreeNode = new ZTreeNode();
zTreeNode.setId("$");
zTreeNode.setpId("root");
zTreeNode.setName("root");
zTreeNode.setDepth(0);
zTreeNode.setPath("$");
traverseTree(rootJson, zTreeNode, zTreeNodes);


    public static void traverseTree(Object rootJson, ZTreeNode zTreeNode, List<ZTreeNode> zTreeNodes) {
        if (rootJson instanceof Map) {
            for (Map.Entry<String, Object> stringObjectEntry : ((Map<String, Object>) rootJson).entrySet()) {
                ZTreeNode zTreeNodeTemp = new ZTreeNode();
                zTreeNodeTemp.setDepth(zTreeNode.getDepth() + 1);
                zTreeNodeTemp.setPath(zTreeNode.getPath() + "." + stringObjectEntry.getKey());
                zTreeNodeTemp.setId(zTreeNodeTemp.getPath());
                zTreeNodeTemp.setName(stringObjectEntry.getKey());
                zTreeNodeTemp.setpId(zTreeNode.getPath());
                zTreeNodes.add(zTreeNodeTemp);
                traverseTree(stringObjectEntry.getValue(), zTreeNodeTemp, zTreeNodes);
            }
        } else if (rootJson instanceof List) {
            List json = (List) rootJson;
            for (int i = 0; i < json.size(); i++) {
                Object obj = json.get(i);
                ZTreeNode zTreeNodeTemp = new ZTreeNode();
                zTreeNodeTemp.setDepth(zTreeNode.getDepth() + 1);
                zTreeNodeTemp.setPath(zTreeNode.getPath() + "[" + i + "]");
                zTreeNodeTemp.setId(zTreeNodeTemp.getPath());
                zTreeNodeTemp.setName(zTreeNode.getName() + "[" + i + "]");
                zTreeNodeTemp.setpId(zTreeNode.getPath());
                zTreeNodes.add(zTreeNodeTemp);
                traverseTree(obj, zTreeNodeTemp, zTreeNodes);
            }
        } else {
            // do nothing
        }
    }

3.利用zTree展示结点为可视化树,点击对应树的结点即可获取对应结点的JsonPath

前端代码:

复制代码
let zTreeObj;
// zTree 的参数配置
let setting = {
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        onClick: zTreeOnClick
    }
};
zTreeObj = $.fn.zTree.init($("#using_json"), setting, zNodes);
zTreeObj.expandAll(true);

4.扩展:将结点信息反向解析

递归解析zNodes+利用nestable插件可视化展示,效果如下:

前端代码:

复制代码
        let detailResult = JSON.parse(zNodes);
        let nestableContent = $('<ol class="dd-list"></ol>');
        let dataId = 0;
    // 遍历解析Json
    function parseJson(jsonObj, nestableContent, dataId) {
        for (let key in jsonObj) {

            let element = jsonObj[key];
            if (element === null) {
                element = "null";
            }
            if (element.length > 0 && typeof (element) == "object" || typeof (element) == "object") {
                
                var li = $('<li class="dd-item" data-id="' + dataId + '"></li>');
                $(li).append('                   <div class="dd-handle">' +
                    '                       <span class="bg-muted p-xs b-r-sm">' + key + '</span>' +
                    '                   </div>').append('<ol class="dd-list"></ol>').appendTo(nestableContent);
                parseJson(element, $(li).children().eq(1), dataId);
            } else {
                dataId++;
                $('<li class="dd-item" data-id="' + dataId + '"></li>').append('                   <div class="dd-handle">' +
                    '                       <span class="bg-muted p-xs b-r-sm">' + key + '</span>' + element +
                    '                   </div>').appendTo(nestableContent);
            }

        }
    }

作者:京东科技 周波

来源:京东云开发者社区 转载请注明来源

相关推荐
CodexDave4 小时前
Python 自动化接单实战(一):把 CSV 需求做成配置驱动解析器
java·python·自动化·json·数据清洗·python自动化·csv处理
今夜有雨.1 天前
C++JSON 解析器
c++·笔记·后端·学习·json
用户657094163301 天前
Kotlin Moshi库 全面使用指南
json
海兰2 天前
【高速缓存】RedisVL 存储类型选择指南:Hash 与 JSON
人工智能·redis·算法·缓存·json·哈希算法
减瓦2 天前
Jackson 使用指南
java·spring boot·json
制造数据与AI践行者老蒋3 天前
离谱!PromptTemplate 遇上 JSON,花括号直接引发解析战争
数据库·microsoft·json
chenjingming6663 天前
JWT(JSON Web Token)有效期查看登录过期时间
json
绘梨衣的sakura路4 天前
Fastjson ≤ 1.2.83 新型 RCE 漏洞深度分析:三层绕过机制与完整利用链
安全·web安全·json
江湖十年4 天前
Go 语言中 YAML to JSON 踩坑笔记
后端·go·json
前网易架构师-高司机4 天前
带标注的扑克牌识别数据集,识别率99.5%,3083张图,支持yolo,coco json,voc xml,文末有模型训练代码
xml·yolo·json·数据集·数字·扑克牌·纸牌