Python请求:从返回的JSON字符串中获取属性 [英] Python requests: get attributes from returned JSON string
本文介绍了Python请求:从返回的JSON字符串中获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import requests
r = requests.get('http://httpbin.org/get');
r.text
返回:
u'{\n "url": "http://httpbin.org/get",\n "headers": {\n "Host": "httpbin.org",\n "Accept-Encoding": "gzip, deflate, compress",\n "Connection": "close",\n "Accept": "*/*",\n "User-Agent": "python-requests/2.2.1 CPython/2.7.5 Windows/7",\n "X-Request-Id": "db302999-d07f-4dd6-8c1e-14db45d39fb0"\n },\n "origin": "61.228.172.190",\n "args": {}\n}'
如何获得 origin
和 headers / Host
值?
谢谢
推荐答案
返回的是 JSON 字符串;你需要先解析它才能方便地使用它。如果您拨打 r.json()
而不是 r.text
,请求可以为您执行此操作。
What's being returned is a JSON string; you need to parse it before you can conveniently use it. Requests can do this for you if you call r.json()
instead of r.text
.
然后这只是做的事情:
resp = r.json()
print resp['origin']
print resp['headers']['Host']
这篇关于Python请求:从返回的JSON字符串中获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文