无法从与 json 一起工作的 URL api 获取信息?

Can't get the information from a URL api working with json?

我想从这个 url 中获取 api 信息: https://api.binance.com/api/v1/ticker/24hr 我需要告诉一个符号 (ETHBTC) 并获得最后的价格。

import requests

binance = requests.get("https://api.binance.com/api/v1/ticker/24hr")
e = binance.json()
print(e['ETHBTC']['lastPrice'])

错误:

Traceback (most recent call last):
  File "C:\Users\crist\Documents\Otros\Programacion\Python HP\borrar.py", line 6, in <module>
    print(e['ETHBTC']['lastPrice'])
TypeError: list indices must be integers or slices, not str

因为您没有在请求中指定您想要的货币对,Binance API 返回列表中所有货币对的详细信息,如下所示:

[
    { Pair 1 info },
    { Pair 2 info },
    { etc.        }
]

因此您需要仅请求您想要的配对的详细信息,或者在您已经获取的列表中找到您想要的配对的详细信息。

要仅请求您想要的那对,您可以将 Requests 的 URL 参数 as an argument 用于您的 get 请求:

myparams = {'symbol': 'ETHBTC'}
binance = requests.get("https://api.binance.com/api/v1/ticker/24hr", params=myparams)
e = binance.json()
print(e['lastPrice'])

或者,要在您已经获取的列表中找到您想要的配对,您可以遍历列表。第一个选项是要走的路,除非你想看很多不同的对。

binance = requests.get("https://api.binance.com/api/v1/ticker/24hr")
e = binance.json()
for pair in e:
    if pair['symbol'] == 'ETHBTC':
        print(pair['lastPrice'])