TypeError:列表索引必须是整数或切片,而不是解析json请求时的str

问题描述 投票:0回答:1

我有一些问题,我学习使用请求和json但我有这个问题

r2 = requests.get('https://poloniex.com/public?command=returnTicker') usdt_btc_ask = r2.json(['USDT_BTC']['lowestAsk'])

和错误

TypeError: list indices must be integers or slices, not str

这段代码没有错误

r1 = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json') print(r1.json()['time']['updated']['bpi']['USD']['rate_float'])

如何用这句话来解决这个问题?

python json python-3.x
1个回答
0
投票

您可以通过执行requests.getreq.json()获得响应,它将为您提供可以迭代的字典。

在你的情况下,json_obj['time']['updated']给你一个字符串,而不是字典,所以你不能在它上面做json_obj['time']['updated']['bpi']

import requests

r1 = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
json_obj = r1.json()
print(json_obj['time']['updated'])
#Apr 20, 2019 14:43:00 UTC
© www.soinside.com 2019 - 2024. All rights reserved.