导言:一般场景下,我们使用Python的内置json库,就能完成大部分的解析和处理JSON格式。
Python内置库:编码和解码 JSON 对象 - json
简介:JsonPath 对于 JSON 来说,相当于 XPath 对于 XML,用来解析多层嵌套的json数据;JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括:Javascript, Python, PHP 和 Java。
官方文档:
http://goessner.net/articles/JsonPathpip安装:
pip install jsonpath使用案例:
1、模糊匹配
2、不存在匹配的结果
3、只匹配出单个结果
4、取某个数据的原始方法
import jsonpathrelation = [{'id': 1, 'label': 'a1', 'children': [], "age": 20},{'id': 2, 'label': 'a2', 'children': [{'id': 3, 'label': 'a3','children': [{'id': 4, 'label': 'a4', 'children': []},{'id': 5, 'label': 'a5','children': [{'id': 7, 'label': 'a7', 'children': []},{'id': 8, 'label': 'a8','children': []}]}]},{'id': 6, 'label': 'a6', 'children': []}]}]# 嵌套n层也能取到所有标签信息,$表示最外层的{},..表示模糊匹配# 查找顺序,第一个 > 第一个的子节点,直到没有。res1 = jsonpath.jsonpath(relation, '$..label') # ['a1', 'a2', 'a3', 'a4', 'a5', 'a7', 'a8', 'a6']res2 = jsonpath.jsonpath(relation, '$..id') # [1, 2, 3, 4, 5, 7, 8, 6]res3 = jsonpath.jsonpath(relation, '*.id') # [1, 2] 匹配所有元素节点print(res1)print(res2)print(res3)# 如果不存在匹配的结果,则返回 Falseres4 = jsonpath.jsonpath(relation, '$..name')print(res4)# 如果只匹配出单个结果,依然会放入一个列表res5 = jsonpath.jsonpath(relation, '$..age') # [20]print(res5)# 取某个数据的原始方法:通过查找字典中的key以及list方法中的下标索引res6 = relation[1]["children"][0]["children"][1]["label"]print(res6) # a5
遍历的顺序:深度优先遍历
PS1:二叉树的深度遍历
沿着树的深度遍历结点,尽可能深的搜索树的分支。如果当前的节点所在的边都被搜索过,就回溯到当前节点所在的那条边的起始节点。一直重复直到进行到发现源节点所有可达的节点为止。
PS2:JsonPath与XPath语法对比
| Xpath | JSONPath | 描述 |
|---|---|---|
| / | $ | 跟节点 |
| . | @ | 现行节点 |
| / | . or [] | 取子节点 |
| .. | n/a | 就是不管位置,选择所有符合条件的条件 |
| * | * | 匹配所有元素节点 |
| [] | [] | 迭代器标示(可以在里面做简单的迭代操作,如数组下标,根据内容选值等) |
| | | [,] | 支持迭代器中做多选 |
| [] | ?() | 支持过滤操作 |
| n/a | () | 支持表达式计算 |
| () | n/a | 分组,JsonPath不支持 |