Python 请求:从返回的 JSON 字符串获取属性

问题描述 投票:0回答:1
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
值?

python json http python-requests
1个回答
31
投票

返回的是一个 JSON 字符串;你需要先解析它,然后才能方便地使用它。如果您调用

requests
而不是
r.json()
r.text
库可以为您执行此操作。

resp = r.json()
print resp['origin']
print resp['headers']['Host']
© www.soinside.com 2019 - 2024. All rights reserved.