Python jsonpath库处理JSON数据
jsonpath官方文档:https://goessner.net/articles/JsonPath/
1.语法:
2.bookstore.xml文件案例:
3.安装第三方库 pip install jsonpath
查看 pip list
4.json文件
code:
#使用jsonpath方法
def usejsonpath():
#1.url
url='https://www.lagou.com/lbs/getAllCitySearchLabels.json'
#2.请求头信息
headers={
'User-Agent':ua.random
}
#3.响应数据
res=requests.get(url,headers=headers)
# print(res.text)
#4.将json字符串转换成python字典
dic=json.loads(res.text)
print(dic)
# 第一种:通过jsonpath
# 提取A里面的所有name元素
#$.根节点content所有数据
# result =jsonpath(dic,'$.content')
#$..A的数据
# result =jsonpath(dic,'$..A')
#$..A的name数据
# result =jsonpath(dic,'$..A[*].name')
# 获取到所有的name
# $ 代表从根节点开始
# ..是不管什么位置
result =jsonpath(dic,'$..name')
# print(result)
# 第二种:通过字典的键取值
resBList=dic['content']['data']['allCitySearchLabels']['B']
# print(resBList)
# #循环列表
for res in resBList:
print(res)
# print(res['name'])
总之: 使用了jsonpath与字典取值,但比较一下,其实jsonpath要简单,而字典就是要层层进入,再循环遍历。
还没有评论,来说两句吧...