【问题标题】:TypeError: string indices must be integers when making rest api request类型错误:发出 REST API 请求时,字符串索引必须是整数
【发布时间】:2021-09-26 07:28:17
【问题描述】:

当我尝试解析一个 rest api 数据时, 它引发了TypeError

这是我的代码:

def get_contracts():

    response_object = requests.get(
        "https://testnet-api.phemex.com/md/orderbook?symbol=BTCUSD"
    )
    print(response_object.status_code)

    for contract in response_object.json()["result"]["book"]:
        print(contract["asks"])


get_contracts()

任何提示或解决方案都将受到欢迎。提前致谢。

编辑/更新:

由于某种原因,我无法选择上述格式的特定键,只有当我这样做时才有可能:

data = response_object.json()['result']['book']['asks']

  print(data)

我将尝试解决我的代码。感谢所有帮助过的人。

【问题讨论】:

    标签: python json request rest


    【解决方案1】:

    此代码审查可能会对您有所帮助:

    import requests
    
    url = "https://testnet-api.phemex.com/md/orderbook?symbol=BTCUSD"
    response_object = requests.get(url)
    
    data = response_object.json()
    # Printing your data helps to inspect the structure
    # print(data)
    
    # This is the list you are looking for:
    asks = data['result']['book']['asks']
    
    for ask in asks:
        print(ask)
    

    【讨论】:

    • 我试过你的方法,我得到错误 TypeError: list indices must be integers or slices, not str.
    【解决方案2】:

    您需要迭代询问,而不是预订。
    您有一个嵌套字典,其中 asks 是一个嵌套列表。
    如果您只需单击获得的链接,或打印出您的 response_object.json(),您就会看到结构。

    for foo in response_object.json()['result']['book']['asks']:
        print(foo)
    

    虽然通常最好将你的 response_object 分配给一个变量。

    data = response_object.json()
    
    for foo in data['result']['book']['asks']:  
        print(foo)
    

    【讨论】:

    • 我得到“类型错误:列表索引必须是整数或切片,而不是 str”如果我输入了太多这样的键
    • 你想得到什么?只有asks and bidsresult > book 中。所有其他键都有单个字符串或整数值,无需迭代即可直接访问
    【解决方案3】:

    看起来您正在尝试访问不存在的东西,因此出现 KeyError。

    我会调试,一个简单的打印,你作为答案得到的 JSON 对象,并确保你试图访问的密钥在那里。

    【讨论】:

      猜你喜欢
      • 2023-02-03
      • 2022-08-09
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 2021-11-10
      • 1970-01-01
      • 2013-09-04
      相关资源
      最近更新 更多