python jsonpath-rw_Python使用jsonpath-rw模块处理Json对象操作示例
本文實(shí)例講述了Python使用jsonpath-rw模塊處理Json對(duì)象操作。分享給大家供大家參考,具體如下:
這兩天在寫一個(gè)爬蟲,需要從網(wǎng)站返回的json數(shù)據(jù)提取一些有用的數(shù)據(jù)。
向url發(fā)起請(qǐng)求,返回的是response,在python3中,response.content是二進(jìn)制bytes類型的,需要用decode()轉(zhuǎn)成unicode的str類型
#如果用的requests發(fā)的請(qǐng)求
import json
response = requests.get(url,headers=self.headers)
response = response.content.decode()
response = json.loads(response) #轉(zhuǎn)成json對(duì)象,在python里也就是dict類型
#如果用的scrapy.Request發(fā)的請(qǐng)求
import json
import scrapy
response = scrapy.Request(url,headers=self.headers)
response = response.text.decode()
response = json.loads(response) #轉(zhuǎn)成json對(duì)象,在python里也就是dict類型
也就是說處理json對(duì)象其實(shí)可以和處理dict一樣,那就要用到很多中括號(hào),而且取值也只能取單個(gè)精確的值。一點(diǎn)都不靈活
用過xpath和css選擇器的人當(dāng)然會(huì)覺得這種方法很笨重。
而恰巧json也有類型的選擇器:jsonpath
但是需要注意的是,python的庫(kù)并不是jsonpath(還真有這個(gè)庫(kù),但是不知如何使用,官方也沒有給出python的使用文檔),真正在python中可以使用的庫(kù)是:jsonpath-rw
下面只列下簡(jiǎn)單常用的基本方法
使用示例
>>> from jsonpath_rw import jsonpath, parse
>>> json_obj = {"student":[{"male":176,"female":162},{"male":174,"female":159}]}
>>> jsonpath_expr = parse("student[*].male")
>>> male = jsonpath_expr.find(json_obj)
>>> male #返回的是list,但是不是我們想要的值
[DatumInContext(value=176, path=Fields('male'), context=DatumInContext(value={'male': 176, 'female': 162}, path=, context=DatumInContext(value=[{'male': 176, 'female': 162}, {'male': 174, 'female': 159}], path=Fields('student'), context=DatumInContext(value={'student': [{'male': 176, 'female': 162}, {'male': 174, 'female': 159}]}, path=This(), context=None)))), DatumInContext(value=174, path=Fields('male'), context=DatumInContext(value={'male': 174, 'female': 159}, path=, context=DatumInContext(value=[{'male': 176, 'female': 162}, {'male': 174, 'female': 159}], path=Fields('student'), context=DatumInContext(value={'student': [{'male': 176, 'female': 162}, {'male': 174, 'female': 159}]}, path=This(), context=None))))]
#想要獲取值,要用如下方法
>>> [match.value for match in male]
[176, 174]
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python jsonpath-rw_Python使用jsonpath-rw模块处理Json对象操作示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux常见基础服务,常用的linux
- 下一篇: 计算机网络技术俄罗斯方块,《The Te