Skip to content

Commit

Permalink
jsonpath语法的基本应用
Browse files Browse the repository at this point in the history
  • Loading branch information
JLUVicent committed Sep 15, 2021
1 parent d6f3c53 commit 24b6a3a
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
31 changes: 31 additions & 0 deletions 20_解析_jsonpath.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{ "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
}
}
}
47 changes: 47 additions & 0 deletions 20_解析_jsonpath.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@


import json
import jsonpath

# 书店所有书的作者
obj = json.load(open('20_解析_jsonpath.json', 'r', encoding='utf-8'))
# print(obj)
# book后面有个通配符*用来表示所有书,若为0表示第一本书,以此类推。
# author_list = jsonpath.jsonpath(obj, '$.store.book[*].author')


# # 所有的作者 注意和上面的区别
# author_list = jsonpath.jsonpath(obj, '$..author')


# print(author_list)

# store下面的所有元素
# tag_list = jsonpath.jsonpath(obj, '$.store.*')
# print(tag_list)

# store所有东西的price
# price_list = jsonpath.jsonpath(obj, '$.store..price')
# print(price_list)

# 第三本书
# book = jsonpath.jsonpath(obj, '$..book[2]')
# print(book)

# 最后一本书
# book = jsonpath.jsonpath(obj, '$..book[(@.length-1)]')
# print(book)

# 前两本书
# book_list = jsonpath.jsonpath(obj, '$..book[0,1]')
# book_list = jsonpath.jsonpath(obj, '$..book[:2]')
# print(book_list)

# 条件过滤需要在()前面添加?
# 过滤出所有包含版本号isbn的书
# book_list = jsonpath.jsonpath(obj, '$..book[?(@.isbn)]')
# print(book_list)

# 哪本书超过了10块
book_list = jsonpath.jsonpath(obj, '$..book[?(@.price>10)]')
print(book_list)

0 comments on commit 24b6a3a

Please sign in to comment.