【问题标题】:Python requests: get attributes from returned JSON stringPython 请求:从返回的 JSON 字符串中获取属性
【发布时间】:2014-06-07 13:15:40
【问题描述】:
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}'

如何获取originheaders/Host 值?

【问题讨论】:

    标签: python json http python-requests


    【解决方案1】:

    返回的是一个JSON 字符串;您需要先对其进行解析,然后才能方便地使用它。如果您调用 r.json() 而不是 r.text,请求可以为您执行此操作。

    resp = r.json()
    print resp['origin']
    print resp['headers']['Host']
    

    【讨论】:

    • r.text 可能使用了错误的字符编码,请始终使用r.json()
    • 为什么我从 json() 得到字符串?
    • 可能是各种原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多