为什么每次使用json库时都会发生keyerror?

2024-04-26 05:28:59 发布

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

 `import requests
  def price():
    response=requests.get(url+coin)
    res_json=response.json()
    return float(res_json[0]['price_usd'])
 url='https://pro-api.coinmarketcap.com/v1/ticker/'
 coin="bitcoin"
 price()`

--------------------------------------------------------------------------- KeyError Traceback (most recent call

last) in 6 url='https://pro-api.coinmarketcap.com/v1/ticker/' 7 coin="bitcoin" ----> 8 price()

in price() 3 response=requests.get(url+coin) 4 res_json=response.json() ----> 5 return float(res_json[0]['price_usd']) 6 url='https://pro-api.coinmarketcap.com/v1/ticker/' 7 coin="bitcoin"

KeyError: 0


Tags: httpscomapijsonurlresponseresrequests
2条回答

此API如上所述进行折旧,运行以下代码,返回的字典声明相同的内容

{'statusCode': 410, 'error': 'Gone', 'message': 'WARNING: This API is now offline. Please switch to the new CoinMarketCap API. (https://pro.coinmarketcap.com/migrate/)'}

import requests
import json
TICKER_API_URL = 'https://api.coinmarketcap.com/v1/ticker/'
def get_latest_crypto_price(crypto):

  response = requests.get(TICKER_API_URL+crypto)
  response_json = response.json()

  return response_json
price = get_latest_crypto_price('bitcoin')

print(price)

因为coinmarketcap.com上的v1api现在已被弃用,所以关闭并在每个请求上返回{'statusCode': 404, 'error': 'Not Found', 'message': 'Not Found'}

相关问题 更多 >