【问题标题】:TypeError with json data in pythonpython中带有json数据的TypeError
【发布时间】:2014-05-16 16:16:52
【问题描述】:

我有一个简单的 Python 代码,用于从交易所输入要价,在尝试运行以下代码时,我得到了 TypeError: unhashable type: 'dict'。我不确定我如何在 python 中处理 json 数据。

import requests

response = requests.get('https://bittrex.com/api/v1/public/getticker?market=BTC-SHIBE')
jdata = response.json()

assert response.status_code == 200

print jdata[{u'result':{u'Ask'}}]

【问题讨论】:

    标签: python python-2.7 python-requests


    【解决方案1】:

    您访问结果字典不正确。如果您想访问要价,请使用:

    print jdata['result']['Ask']
    

    'result' 为您提供嵌套字典,然后您可以访问与 'Ask' 关联的值。

    您可以在出现错误响应时要求响应引发异常,而不是使用断言:

    import requests
    
    response = requests.get('https://bittrex.com/api/v1/public/getticker?market=BTC-SHIBE')
    response.raise_for_status()  # raises an exception if not a 2xx or 3xx response
    
    jdata = response.json()
    
    print jdata['result']['Ask']
    

    您应该在尝试访问 JSON 数据之前执行此操作。

    演示:

    >>> import requests
    >>> response = requests.get('https://bittrex.com/api/v1/public/getticker?market=BTC-SHIBE')
    >>> response.raise_for_status()
    >>> jdata = response.json()
    >>> print jdata['result']['Ask']
    9.2e-07
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2018-12-04
      • 2014-11-02
      • 2016-09-03
      • 2011-03-29
      相关资源
      最近更新 更多