从api dict响应获取值

2024-04-20 07:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我将响应存储到一个变量中,尝试了几种方法来提取lastPrice值,包括print(值[1])print(值['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}]

使用值[1]只返回打印中的第一个字母。所以对于ex[1]返回{和使用['lastPrice']返回 TypeError: string indices must be integers


Tags: 方法httpsimportcomapigetvaluewww
1条回答
网友
1楼 · 发布于 2024-04-20 07:18:23

返回值是JSON字符串,可以使用^{}将其解码为python dict。结果包含带有单个元素的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'])

相关问题 更多 >