jsonpath的安装
pip install jsonpath
jsonpath的使用:
obj = json.load(open('json文件', 'r', encoding='utf-8'))
ret = jsonpath.jsonpath(obj, 'jsonpath语法')
json文件:
{ "store": {
"book": [
{ "category": "末世",
"author": "晨星LL",
"title": "这游戏也太真实了",
"price": 8.95
},
{ "category": "玄幻",
"author": "辰东",
"title": "遮天",
"price": 12.99
},
{ "category": "御兽",
"author": "清泉流响",
"title": "不科学御兽",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "科幻",
"author": "我吃西红柿",
"title": "吞噬星空",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"author": "车厂",
"color": "blue",
"price": 19.95
}
}
}
# *代表全部 可以根据下标来获取第几本书
book_list = jsonpath.jsonpath(obj, '$.store.book[*].author')
print(book_list)
book_list = jsonpath.jsonpath(obj, '$..author')
print(book_list)
book_list = jsonpath.jsonpath(obj, '$.store[*]')
print(book_list)
book_list = jsonpath.jsonpath(obj, '$.store..price')
print(book_list)
book_list = jsonpath.jsonpath(obj, '$..book[2]')
print(book_list)
book_list = jsonpath.jsonpath(obj, '$..book[(@.length-1)]')
print(book_list)
# 两种写法
book_list = jsonpath.jsonpath(obj, '$..book[0,1]')
book_list = jsonpath.jsonpath(obj, '$..book[:2]')
print(book_list)
book_list = jsonpath.jsonpath(obj, '$..book[?(@.isbn)]')
print(book_list)
book_list = jsonpath.jsonpath(obj, '$..book[?(@.price>10)]')
print(book_list)
参考:https://blog.csdn.net/Obstinate_L/article/details/125294971