【问题标题】:Getting value from api dict response从 api dict 响应中获取价值
【发布时间】:2019-10-03 22:40:07
【问题描述】:

我正在使用带有 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

【问题讨论】:

标签: python list dictionary indexing tuples


【解决方案1】:

你的返回值是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'])

【讨论】:

  • ty 我非常尝试将其转换为 json 并使用相同的方法来获取值,但我没有想到事先添加 [0],认为这是一个简单的修复。
  • 是的,我接受了抱歉,它说我必须等待 10 分钟,因为它是一个新帐户来寻求帮助。
猜你喜欢
  • 1970-01-01
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
相关资源
最近更新 更多