{"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}}}
# -*- coding:utf-8 -*-# 作者:虫无涯# 日期:2023/7/31 # 文件名称:json_path.py# 作用:jsonpath# 联系:VX(NoamaNelson)# 博客:https://blog.csdn.net/NoamaNelsonimport jsonpath as jp
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}}}
# 获取店内所有书籍的作者
author = jp.jsonpath(data,'$.store.book[*].author')print(author)# 输出['Nigel Rees','Evelyn Waugh','Herman Melville','J. R. R. Tolkien']
# 获取所有作者
all_aythor = jp.jsonpath(data,'$..author')print(all_aythor)# 输出['Nigel Rees','Evelyn Waugh','Herman Melville','J. R. R. Tolkien']
# 获取store的所有元素
book_bicycle = jp.jsonpath(data,'$.store.*')print(book_bicycle)# 输出[[{'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}],{'color':'red','price':19.95}]
# 获取最后一本书的所有信息
last_book = jp.jsonpath(data,'$.store..book[-1:]')print(last_book)# 输出:[{'category':'fiction','author':'J. R. R. Tolkien','title':'The Lord of the Rings','isbn':'0-395-19395-8','price':22.99}]
# 过滤出价格低于10的书
p = jp.jsonpath(data,'$.store..book[?(@.price<10)]')print(p)# 输出:[{'category':'reference','author':'Nigel Rees','title':'Sayings of the Century','price':8.95},{'category':'fiction','author':'Herman Melville','title':'Moby Dick','isbn':'0-553-21311-3','price':8.99}]