什么是JSONPath?
JSONPath 是一个表达式语言来解析 JSON 数据. 它非常类似于XPath 表达式语言来解析 XML 数据. 这个想法是解析 JSON 数据并获得您想要的值. 这是更有效的内存,因为我们不需要读取完整的 JSON 数据。
Python JSONPath 图书馆
在Python中有许多JSONPath库。
- jsonpath:它是 Perl 的端口,以及 JSONPath 的 JavaScript 版本
- jsonpath-rw: JSONPath 表达式的完整 Python 实现。 JSONPath 表达式是第一类对象,易于分析、转换、解析、打印和扩展。 jsonpath-rw-ext模块提供了一些额外的扩展来扩展其功能性
- jsonpath-ng:旨在符合标准的 JSONPath 最终实现,包括数学和二进制比较操作员。本库结合了 jsonpath-rw和 jsonpath-w-ext模块,并进一步增强了
使用哪个Python JSONPath库?
该 jsonpath-ng模块是最全面的,纯粹是用Python编写的,它支持Python 2和Python 3.因此,我们将使用此模块用于Python JSONPath示例。
安装 jsonpath-ng 模块
我们可以使用 PIP 安装 jsonpath-ng 模块。
1$ pip3.7 install jsonpath-ng
使用 JSONPath 解析简单的 JSON 数据
让我们来看看一个简单的例子来解析 JSON 数据并获得所需的属性值。
1import json
2
3from jsonpath_ng import jsonpath, parse
4
5json_string = '{"id":1, "name":"Pankaj"}'
6json_data = json.loads(json_string)
7
8jsonpath_expression = parse('$.id')
9
10match = jsonpath_expression.find(json_data)
11
12print(match)
13print("id value is", match[0].value)
出发点:
1[DatumInContext(value=1, path=Fields('id'), context=DatumInContext(value={'id': 1, 'name': 'Pankaj'}, path=Root(), context=None))]
2id value is 1
我们正在使用 [json 模块]( / 社区 / 教程 / python-parse-json-dumps-loads)将 JSON 字符串转换为 [字典]( / 社区 / 教程 / python-字典)。
使用 JSONPath 表达式对列表进行分析
JSON 密钥可以包含值列表. 我们可以使用 JSONPath 表达式来分析列表并获取值列表. 假设我们有一个 JSON 文件 "db.json" 具有以下内容。
1{
2 "employees": [
3 {
4 "id": 1,
5 "name": "Pankaj",
6 "salary": "10000"
7 },
8 {
9 "name": "David",
10 "salary": "5000",
11 "id": 2
12 }
13 ]
14}
我们想要分析这个 JSON 文件并获得员工 ID 列表,我们可以使用 JSONPath 表达式来非常容易地获取这些数据。
1import json
2from jsonpath_ng import jsonpath, parse
3
4with open("db.json", 'r') as json_file:
5 json_data = json.load(json_file)
6
7print(json_data)
8
9jsonpath_expression = parse('employees[*].id')
10
11for match in jsonpath_expression.find(json_data):
12 print(f'Employee id: {match.value}')
输出:
1{'employees': [{'id': 1, 'name': 'Pankaj', 'salary': '10000'}, {'name': 'David', 'salary': '5000', 'id': 2}]}
2Employee id: 1
3Employee id: 2
推荐阅读: Python f-strings – PEP 498 – Literal String Interpolation
如果您想将数据列入列表,您可以使用 [Python 列表理解]( / 社区 / 教程 / Python-列表理解)。
1emp_ids_list = [match.value for match in jsonpath_expression.find(json_data)]
2print(emp_ids_list) # [1, 2]
结论
JSONPath为我们提供了一个简单的方法来分析 JSON 数据并提取特定值,当 JSON 数据庞大,我们对只有少数值感兴趣时,它非常有用。
参考
- jsonpath.com:测试 JSONPath 表达式的有效性
- jsonlint.com:验证 JSON 数据