基于 jsonpath-use 的 JSON 数据查找
最编程
2024-09-30 14:29:15
...
测试数据
import jsonpath
import json
json_data = '''
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
'''
data = json.loads(json_data)
从根目录递归
# 从根目录递归匹配键bicycle
bicycle = jsonpath.jsonpath(data, '$..bicycle')
print(bicycle)
# [{'color': 'red', 'price': 19.95}]
$
表示根目录,..
表示遍历。
键过滤
# 从根目录递归匹配book,并且当前子键是isbn
isbn = jsonpath.jsonpath(data, '$..book[?(@.isbn)]')
print(isbn)
# [{'category': 'fiction', 'author': 'Herman Melville', 'title': 'Moby Dick', 'isbn': '0-553-21311-3', 'price': 8.99}, {'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]
?()
用来过滤。
取值
author = jsonpath.jsonpath(data, '$..author')
print(author)
# ['Nigel Rees', 'Evelyn Waugh', 'Herman Melville', 'J. R. R. Tolkien']
author下面是键值对的值。
多选
#提取bicycle中color,price
color = jsonpath.jsonpath(data, '$..bicycle[color,price]]')
print(color)
# ['red', 19.95]
[,]
可以填写多个键,用来多选。
[]和.写法
# 跟$..bicycle.price一样
price = jsonpath.jsonpath(data, '$..bicycle[price]')
print(price)
#[19.95]
.
不能多选。
值过滤
# 取价格小于15的book
price = jsonpath.jsonpath(data, '$..book[?(@.price<15)]')
print(price)
# [{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}, {'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 12.99}, {'category': 'fiction', 'author': 'Herman Melville', 'title': 'Moby Dick', 'isbn': '0-553-21311-3', 'price': 8.99}]
第几个
# 取第二个
book1 = jsonpath.jsonpath(data, '$..book[1]')
print(book1)
# [{'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 12.99}]
# 取前两个
book2 = jsonpath.jsonpath(data, '$..book[:2]')
print(book2)
# [{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}, {'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 12.99}]
[]
里的数字从0开始。
上一篇: 入门级网络安全工程师的学习内容
下一篇: 围棋中的深度复制:概念、实现和限制
推荐阅读
-
基于 Spark 的汽车行业大数据分析与可视化系统-摘要
-
基于 jsonpath-use 的 JSON 数据查找
-
基于大数据的大学新生数据可视化分析系统--代码
-
助农小程序 | 助农扶贫系统 | 基于 java 的助农扶贫系统小程序设计与实现(源代码 + 数据库 + 文档)
-
基于 MinIO 对象存储,确保 Rancher 数据的安全性
-
labelme 2021:简化 JSON 到数据集转换的批处理实现方式
-
实战!基于JSP的登录注册功能开发(包含增删改查及网页、数据库操作)
-
在JSP中使用Java遍历JSON数据的循环方法
-
使用JavaScript解析JSON数据并避免A标签的默认跳转功能
-
使用jQuery进行表单提交并处理返回的JSON数据