Js解析Json数据获取元素JsonPath与深度

2024-06-02 19:38

本文主要是介绍Js解析Json数据获取元素JsonPath与深度,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原文出处:http://www.yund.tech/zdetail.html?type=1&id=c2b21696839eccdef2e9b085b9e064f6

作者: jstarseven


JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括:Javascript, Python, PHP 和 Java,JsonPath 对于 JSON 来说,相当于 XPATH 对于 XML。

  • JsonPath与Xpath用法对比
  • Java使用Jsonpath解析json数据
  • Js获取Json每个节点的JsonPath
  • 将输出结果转换成树形结构

1.JsonPath与Xpath用法对比

XPathJSONPath描述
/$根节点
.@现行节点
/.or[]取子节点
n/a取父节点,Jsonpath未支持
//就是不管位置,选择所有符合条件的条件
**匹配所有元素节点
@n/a根据属性访问,Json不支持,因为Json是个Key-value递归结构,不需要。
[][]迭代器标示(可以在里边做简单的迭代操作,如数组下标,根据内容选值等)
|[,]支持迭代器中做多选。
[]?()支持过滤操作.
n/a()支持表达式计算
()n/a分组,JsonPath不支持

2.Java使用Jsonpath解析json数据

1)引入fastjson依赖

<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.6</version>
</dependency>

2)java简单的解析案例

public class JsonPath {public static void main(String[] args) {String jsonStr = "{\n" +"  \"store\": {\n" +"    \"book\": [\n" +"      {\n" +"        \"category\": \"reference\",\n" +"        \"author\": \"Nigel Rees\",\n" +"        \"title\": \"Sayings of the Century\",\n" +"        \"price\": 8.95\n" +"      },\n" +"      {\n" +"        \"category\": \"fiction\",\n" +"        \"author\": \"Evelyn Waugh\",\n" +"        \"title\": \"Sword of Honour\",\n" +"        \"price\": 12.99,\n" +"        \"isbn\": \"0-553-21311-3\"\n" +"      }\n" +"      {\n" +"        \"category\": \"fiction\",\n" +"        \"author\": \"Evelyn Waugh\",\n" +"        \"title\": \"Sword of Honour two\",\n" +"        \"price\": 12.99,\n" +"        \"isbn\": \"0-553-21311-3\"\n" +"      }\n" +"    ],\n" +"    \"bicycle\": {\n" +"      \"color\": \"red\",\n" +"      \"price\": 19.95\n" +"    }\n" +"  }\n" +"}";JSONObject jsonObject = JSON.parseObject(jsonStr);System.out.println("Book:" + JSONPath.eval(jsonObject, "$.store.book"));System.out.println("Book数目:" + JSONPath.eval(jsonObject, "$.store.book.size()"));System.out.println("第一本书title:" + JSONPath.eval(jsonObject, "$.store.book[0].title"));System.out.println("price大于10元的book:" + JSONPath.eval(jsonObject, "$.store.book[price > 10]"));System.out.println("price大于10元的title:" + JSONPath.eval(jsonObject, "$.store.book[price > 10][0].title"));System.out.println("price大于10元的title:" + JSONPath.eval(jsonObject, "$.store.book[price > 10][1].title"));System.out.println("category(类别)为fiction(小说)的book:" + JSONPath.eval(jsonObject, "$.store.book[category = 'fiction']"));System.out.println("bicycle的所有属性值" + JSONPath.eval(jsonObject, "$.store.bicycle.*"));System.out.println("bicycle的color和price属性值" + JSONPath.eval(jsonObject, "$.store.bicycle['color','price']"));}

3.Js获取Json每个节点的JsonPath

1)准备json测试数据

var root = {name: '测试节点',doms: {name: "dom测试",children: [{name: '茶馆',val: 'demo',child: [{"name": "李四", "cal": "ceshi"}, {"name": "王五", "cal": "ceshi"}]},{name: '红与黑',val: 'demo',child: [{"name": "张三", "cal": "ceshi"}, {"name": "张三", "cal": "ceshi"}]}]},children: [{name: '学习',children: []},{name: '电影',children: [{name: '喜剧电影'},{name: '动作电影'}]}]}

2)遍历Json对象获取每个节点的深度与JsonPath

     function traverseTree(node, flat) {var stack = [], res = [];if (!node) return;stack.push({"dom": node, "dep": 0, "path": "$", "name": "根节点"});var tmpNode;while (stack.length > 0) {tmpNode = stack.pop();res.push({"name": tmpNode.name,"pid": tmpNode.pid,"path": tmpNode.path,"dep": tmpNode.dep});traverseNode2(tmpNode, tmpNode.dep);}// 遍历单个节点function traverseNode2(node, dep) {var doc = node.dom;if (Object.prototype.toString.call(doc) === '[object Object]') {for (var val in doc) {var cpath = (node.path + "." + val);stack.push({"dom": doc[val],"dep": (dep + 1),"path": cpath,"pid": node.path,"name": val});}}if (Object.prototype.toString.call(doc) === '[object Array]') {for (let i = 0; i < doc.length; i++) {stack.push({"dom": doc[i],"dep": (dep + 1),"path": (node.path + "[" + i + "]"),"pid": node.path,"name": node.name + "[" + i + "]"});}}}// 树形结构转换function flat2tree(jsonData) {var result = [], temp = {}, i = 0, j = 0, len = jsonData.length;for (; i < len; i++)temp[jsonData[i]['path']] = jsonData[i]for (; j < len; j++) {var cel = jsonData[j]var tcel = temp[cel['pid']]if (tcel) {if (!tcel['children']) {tcel['children'] = [];}tcel['children'].push(cel)} else {result.push(cel);}}return result;}return flat ? flat2tree(res) : res;}

3)测试输出

console.log("res-tree:\n" + JSON.stringify(traverseTree(root, false)));
res-tree:
[{"name":"根节点","path":"$","dep":0},{"name":"children","pid":"$","path":"$.children","dep":1},{"name":"children[1]","pid":"$.children","path":"$.children[1]","dep":2},{"name":"children","pid":"$.children[1]","path":"$.children[1].children","dep":3},{"name":"children[1]","pid":"$.children[1].children","path":"$.children[1].children[1]","dep":4},{"name":"name","pid":"$.children[1].children[1]","path":"$.children[1].children[1].name","dep":5},{"name":"children[0]","pid":"$.children[1].children","path":"$.children[1].children[0]","dep":4},{"name":"name","pid":"$.children[1].children[0]","path":"$.children[1].children[0].name","dep":5},{"name":"name","pid":"$.children[1]","path":"$.children[1].name","dep":3},{"name":"children[0]","pid":"$.children","path":"$.children[0]","dep":2},{"name":"children","pid":"$.children[0]","path":"$.children[0].children","dep":3},{"name":"name","pid":"$.children[0]","path":"$.children[0].name","dep":3},{"name":"doms","pid":"$","path":"$.doms","dep":1},{"name":"children","pid":"$.doms","path":"$.doms.children","dep":2},{"name":"children[1]","pid":"$.doms.children","path":"$.doms.children[1]","dep":3},{"name":"child","pid":"$.doms.children[1]","path":"$.doms.children[1].child","dep":4},{"name":"child[1]","pid":"$.doms.children[1].child","path":"$.doms.children[1].child[1]","dep":5},{"name":"cal","pid":"$.doms.children[1].child[1]","path":"$.doms.children[1].child[1].cal","dep":6},{"name":"name","pid":"$.doms.children[1].child[1]","path":"$.doms.children[1].child[1].name","dep":6},{"name":"child[0]","pid":"$.doms.children[1].child","path":"$.doms.children[1].child[0]","dep":5},{"name":"cal","pid":"$.doms.children[1].child[0]","path":"$.doms.children[1].child[0].cal","dep":6},{"name":"name","pid":"$.doms.children[1].child[0]","path":"$.doms.children[1].child[0].name","dep":6},{"name":"val","pid":"$.doms.children[1]","path":"$.doms.children[1].val","dep":4},{"name":"name","pid":"$.doms.children[1]","path":"$.doms.children[1].name","dep":4},{"name":"children[0]","pid":"$.doms.children","path":"$.doms.children[0]","dep":3},{"name":"child","pid":"$.doms.children[0]","path":"$.doms.children[0].child","dep":4},{"name":"child[1]","pid":"$.doms.children[0].child","path":"$.doms.children[0].child[1]","dep":5},{"name":"cal","pid":"$.doms.children[0].child[1]","path":"$.doms.children[0].child[1].cal","dep":6},{"name":"name","pid":"$.doms.children[0].child[1]","path":"$.doms.children[0].child[1].name","dep":6},{"name":"child[0]","pid":"$.doms.children[0].child","path":"$.doms.children[0].child[0]","dep":5},{"name":"cal","pid":"$.doms.children[0].child[0]","path":"$.doms.children[0].child[0].cal","dep":6},{"name":"name","pid":"$.doms.children[0].child[0]","path":"$.doms.children[0].child[0].name","dep":6},{"name":"val","pid":"$.doms.children[0]","path":"$.doms.children[0].val","dep":4},{"name":"name","pid":"$.doms.children[0]","path":"$.doms.children[0].name","dep":4},{"name":"name","pid":"$.doms","path":"$.doms.name","dep":2},{"name":"name","pid":"$","path":"$.name","dep":1}
]

4.将输出结果转换成树形结构

console.log("res-tree:\n" + JSON.stringify(traverseTree(root, true)));
res-tree:
[{"name":"根节点","path":"$","dep":0,"children":[{"name":"children","pid":"$","path":"$.children","dep":1,"children":[{"name":"children[1]","pid":"$.children","path":"$.children[1]","dep":2,"children":[{"name":"children","pid":"$.children[1]","path":"$.children[1].children","dep":3,"children":[{"name":"children[1]","pid":"$.children[1].children","path":"$.children[1].children[1]","dep":4,"children":[{"name":"name","pid":"$.children[1].children[1]","path":"$.children[1].children[1].name","dep":5}]},{"name":"children[0]","pid":"$.children[1].children","path":"$.children[1].children[0]","dep":4,"children":[{"name":"name","pid":"$.children[1].children[0]","path":"$.children[1].children[0].name","dep":5}]}]},{"name":"name","pid":"$.children[1]","path":"$.children[1].name","dep":3}]},{"name":"children[0]","pid":"$.children","path":"$.children[0]","dep":2,"children":[{"name":"children","pid":"$.children[0]","path":"$.children[0].children","dep":3},{"name":"name","pid":"$.children[0]","path":"$.children[0].name","dep":3}]}]},{"name":"doms","pid":"$","path":"$.doms","dep":1,"children":[{"name":"children","pid":"$.doms","path":"$.doms.children","dep":2,"children":[{"name":"children[1]","pid":"$.doms.children","path":"$.doms.children[1]","dep":3,"children":[{"name":"child","pid":"$.doms.children[1]","path":"$.doms.children[1].child","dep":4,"children":[{"name":"child[1]","pid":"$.doms.children[1].child","path":"$.doms.children[1].child[1]","dep":5,"children":[{"name":"cal","pid":"$.doms.children[1].child[1]","path":"$.doms.children[1].child[1].cal","dep":6},{"name":"name","pid":"$.doms.children[1].child[1]","path":"$.doms.children[1].child[1].name","dep":6}]},{"name":"child[0]","pid":"$.doms.children[1].child","path":"$.doms.children[1].child[0]","dep":5,"children":[{"name":"cal","pid":"$.doms.children[1].child[0]","path":"$.doms.children[1].child[0].cal","dep":6},{"name":"name","pid":"$.doms.children[1].child[0]","path":"$.doms.children[1].child[0].name","dep":6}]}]},{"name":"val","pid":"$.doms.children[1]","path":"$.doms.children[1].val","dep":4},{"name":"name","pid":"$.doms.children[1]","path":"$.doms.children[1].name","dep":4}]},{"name":"children[0]","pid":"$.doms.children","path":"$.doms.children[0]","dep":3,"children":[{"name":"child","pid":"$.doms.children[0]","path":"$.doms.children[0].child","dep":4,"children":[{"name":"child[1]","pid":"$.doms.children[0].child","path":"$.doms.children[0].child[1]","dep":5,"children":[{"name":"cal","pid":"$.doms.children[0].child[1]","path":"$.doms.children[0].child[1].cal","dep":6},{"name":"name","pid":"$.doms.children[0].child[1]","path":"$.doms.children[0].child[1].name","dep":6}]},{"name":"child[0]","pid":"$.doms.children[0].child","path":"$.doms.children[0].child[0]","dep":5,"children":[{"name":"cal","pid":"$.doms.children[0].child[0]","path":"$.doms.children[0].child[0].cal","dep":6},{"name":"name","pid":"$.doms.children[0].child[0]","path":"$.doms.children[0].child[0].name","dep":6}]}]},{"name":"val","pid":"$.doms.children[0]","path":"$.doms.children[0].val","dep":4},{"name":"name","pid":"$.doms.children[0]","path":"$.doms.children[0].name","dep":4}]}]},{"name":"name","pid":"$.doms","path":"$.doms.name","dep":2}]},{"name":"name","pid":"$","path":"$.name","dep":1}]}
]

file

本文由博客群发一文多发等运营工具平台 OpenWrite 发布

这篇关于Js解析Json数据获取元素JsonPath与深度的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python将大量遥感数据的值缩放指定倍数的方法(推荐)

《Python将大量遥感数据的值缩放指定倍数的方法(推荐)》本文介绍基于Python中的gdal模块,批量读取大量多波段遥感影像文件,分别对各波段数据加以数值处理,并将所得处理后数据保存为新的遥感影像... 本文介绍基于python中的gdal模块,批量读取大量多波段遥感影像文件,分别对各波段数据加以数值处

使用MongoDB进行数据存储的操作流程

《使用MongoDB进行数据存储的操作流程》在现代应用开发中,数据存储是一个至关重要的部分,随着数据量的增大和复杂性的增加,传统的关系型数据库有时难以应对高并发和大数据量的处理需求,MongoDB作为... 目录什么是MongoDB?MongoDB的优势使用MongoDB进行数据存储1. 安装MongoDB

在C#中获取端口号与系统信息的高效实践

《在C#中获取端口号与系统信息的高效实践》在现代软件开发中,尤其是系统管理、运维、监控和性能优化等场景中,了解计算机硬件和网络的状态至关重要,C#作为一种广泛应用的编程语言,提供了丰富的API来帮助开... 目录引言1. 获取端口号信息1.1 获取活动的 TCP 和 UDP 连接说明:应用场景:2. 获取硬

Python MySQL如何通过Binlog获取变更记录恢复数据

《PythonMySQL如何通过Binlog获取变更记录恢复数据》本文介绍了如何使用Python和pymysqlreplication库通过MySQL的二进制日志(Binlog)获取数据库的变更记录... 目录python mysql通过Binlog获取变更记录恢复数据1.安装pymysqlreplicat

Linux使用dd命令来复制和转换数据的操作方法

《Linux使用dd命令来复制和转换数据的操作方法》Linux中的dd命令是一个功能强大的数据复制和转换实用程序,它以较低级别运行,通常用于创建可启动的USB驱动器、克隆磁盘和生成随机数据等任务,本文... 目录简介功能和能力语法常用选项示例用法基础用法创建可启动www.chinasem.cn的 USB 驱动

在MyBatis的XML映射文件中<trim>元素所有场景下的完整使用示例代码

《在MyBatis的XML映射文件中<trim>元素所有场景下的完整使用示例代码》在MyBatis的XML映射文件中,trim元素用于动态添加SQL语句的一部分,处理前缀、后缀及多余的逗号或连接符,示... 在MyBATis的XML映射文件中,<trim>元素用于动态地添加SQL语句的一部分,例如SET或W

IDEA如何将String类型转json格式

《IDEA如何将String类型转json格式》在Java中,字符串字面量中的转义字符会被自动转换,但通过网络获取的字符串可能不会自动转换,为了解决IDEA无法识别JSON字符串的问题,可以在本地对字... 目录问题描述问题原因解决方案总结问题描述最近做项目需要使用Ai生成json,可生成String类型

C#实现获取电脑中的端口号和硬件信息

《C#实现获取电脑中的端口号和硬件信息》这篇文章主要为大家详细介绍了C#实现获取电脑中的端口号和硬件信息的相关方法,文中的示例代码讲解详细,有需要的小伙伴可以参考一下... 我们经常在使用一个串口软件的时候,发现软件中的端口号并不是普通的COM1,而是带有硬件信息的。那么如果我们使用C#编写软件时候,如

Oracle数据库使用 listagg去重删除重复数据的方法汇总

《Oracle数据库使用listagg去重删除重复数据的方法汇总》文章介绍了在Oracle数据库中使用LISTAGG和XMLAGG函数进行字符串聚合并去重的方法,包括去重聚合、使用XML解析和CLO... 目录案例表第一种:使用wm_concat() + distinct去重聚合第二种:使用listagg,

C#实现WinForm控件焦点的获取与失去

《C#实现WinForm控件焦点的获取与失去》在一个数据输入表单中,当用户从一个文本框切换到另一个文本框时,需要准确地判断焦点的转移,以便进行数据验证、提示信息显示等操作,本文将探讨Winform控件... 目录前言获取焦点改变TabIndex属性值调用Focus方法失去焦点总结最后前言在一个数据输入表单