Python 为什么每次使用json库时都会发生keyerror? ---------------------------------------------------------------------------KeyError回溯(最近的呼叫
最后)在 6 url=“” 7 coin=“比特币” ---->8价格() 价格() 3响应=请求.get(url+coin) 4 res_json=response.json() ---->5返回浮动(res_json[0]['价格_美元]) 6 url=“” 7 coin=“比特币” 关键错误:0Python 为什么每次使用json库时都会发生keyerror? ---------------------------------------------------------------------------KeyError回溯(最近的呼叫,python,json,bitcoin,Python,Json,Bitcoin,最后)在 6 url=“” 7 coin=“比特币” ---->8价格() 价格() 3响应=请求.get(url+coin) 4 res_json=response.json() ---->5返回浮动(res_json[0]['价格_美元]) 6 url=“” 7 coin=“比特币” 关键错误:0 因为coinmarketcap.com上的v1api现在已被弃用,所以关闭,并在每个请求上返回{'statusCode':404,'error':'Not Found','message':'No
因为coinmarketcap.com上的v1api现在已被弃用,所以关闭,并在每个请求上返回
{'statusCode':404,'error':'Not Found','message':'Not Found'}
。此API如上所述被降级,运行以下代码,返回的字典声明相同的内容
`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()`
如果您打印出
res_json
,您会发现它是一个dict
,而不是数组
,并且没有键0
。如何访问价格键json结构由嵌套列表和字典组成。列表按编号索引,dicts按名称/键索引。向我们展示您尝试过的内容的详细信息。显示您加载的URL、从该URL获取的内容,最后显示您试图解析该URL的代码。
{'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)