从 api 字典响应中获取值



我使用带有 Bitmex API 的请求,我试图从 get 请求中获取 lastPrice 值。

我将响应存储到一个变量中,尝试了几种方法来提取 lastPrice 值,包括 print(value[1]( print(value['lastPrice'](,所有这些都不起作用,我已经在这里阅读了一段时间,似乎找不到正确的工作方法来获取值。 对不起,如果一直问这个问题。

import requests
r = requests.get('https://www.bitmex.com/api/v1/instrument?symbol=XBT&columns=lastPrice&count=1&reverse=true')
value = r.text
print(value)
#print(value[1]) 
#print(value['lastPrice'])

由此产生的输出是

[{"symbol":"XBTUSD","timestamp":"2019-10-03T22:37:13.085Z","lastPrice":8190.5}]

使用 value[1] 只返回打印中的第一个字母。因此,对于 ex [1] 返回 { 并使用 ['lastPrice'] 返回TypeError: string indices must be integers

你的返回值是JSON字符串,你可以用response.json()将其解码为pythondict。结果包含具有单个元素的list,因此您应该引用list的第一个元素,然后按键从dict中获取值:

r = requests.get('https://www.bitmex.com/api/v1/instrument?symbol=XBT&columns=lastPrice&count=1&reverse=true')
value = r.json()
print(value[0]['lastPrice'])

最新更新