每日分享:
每个人的成长就是你的能力和你想要获取的东西不断匹配的过程
目标- 了解jsonpath模块的使用场景
- 掌握jsonpath模块的使用
如果有一个多层嵌套的复杂字典,想要根据key和下标来批量提取value,这是比较困难的。
jsonpath模块可以很好地解决这个问题。
jsonpath可以按照key对pathon字典进行批量数据提取
二、jsonpath模块的使用 2.1 jsonpath模块的安装在终端中输入:
pip install jsonpath
2.2 jsonpath模块提取数据的方法(作用对象为字典)from jsonpath import jsonpath
ret = jsonpath(a, 'jsonpath语法规则的字符串')
例:(jsonpath提取出来的是列表,加上索引即可提取出列表内数据)
from jsonpath import jsonpath
a = {'key1': {'key2': {'key3': {'key4': {'key5': 'python'}}}}}
print(jsonpath(a, '$.key1.key2.key3.key4.key5')[0])
ret = jsonpath(a, '$..key5')[0]
print(ret)
结果:

from jsonpath import jsonpath
import json
# book_dict模拟requests得到的json字符串,需要中json转换为json字典
book_dict = '''{
"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(book_dict)
print(jsonpath(data, '$..color'))
print(jsonpath(data, '$..price'))
结果:
import json
from jsonpath import jsonpath
import requests
url = 'https://www.lagou.com/lbs/getAllCitySearchLabels.json'
headers = {
'user-agent': '替换为你的user-agent'
}
response = requests.get(url=url, headers=headers)
data_dict = json.loads(response.content)
# 找到所有B开头的城市的名字
data = jsonpath(data_dict, '$..B..name')
print(data)
结果: