从JSON Data API中获取特定值

时间:2018-02-13 18:24:35

标签: python json

我完全清楚本网站上还有其他主题,但解决方案对我不起作用。

我正在尝试从此API地址中获取“last”值: excel mockup

在Python中,我尝试了很多不同的脚本,并且自己努力尝试但是我总是得到一个“KeyError”,尽管API中有“last”。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您的回复数据具有以下结构:

$ curl  https://cryptohub.online/api/market/ticker/PLSR/ | json_pp
{
   "BTC_PLSR" : {
      "baseVolume" : 0.00772783,
      "lowestAsk" : 0.00019999,
      "percentChange" : -0.0703703704,
      "quoteVolume" : 83.77319071,
      "last" : 0.000251,
      "id" : 78,
      "highestBid" : 5e-05,
      "high24hr" : 0.000251,
      "low24hr" : 1.353e-05,
      "isFrozen" : "0"
   }
}

即。字典里面的字典,所以要提取你需要的值:

data = response.json()["BTC_PLSR"]
visitors = data["id"]

评论更新:

我不确定我理解你,我做了一个简单的测试,它运行良好:

$ python3 << EOF
> import requests
> url = 'https://cryptohub.online/api/market/ticker/PLSR/'
> response = requests.get(url)
> data = response.json()['BTC_PLSR']
> print('ID ==> ', data['id'])
> EOF
ID ==>  78

如您所见,行print('ID ==> ', data['id'])返回输出ID ==> 78

测试源代码:

import requests
url = 'https://cryptohub.online/api/market/ticker/PLSR/'
response = requests.get(url)
data = response.json()['BTC_PLSR']
print('ID ==> ', data['id'])