I am solving a python problem in which I have to request a JSON file of the current status of bitcoin and from that, I have to fetch the current price of USD, I am stuck on the part where I have to fetch the rate from JSON file which is deep inside some dictonaries which contains a lot of data and I don't know how to get a specific key from them ... here is my code sample (currently I just want to fetch the USD rate and print it)
import sys
from urllib import response
import requests
import json
if len(sys.argv) == 1 :
sys.exit("missing argument!")
elif type(float(sys.argv[1])) != float :
sys.exit("argument is not number")
response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
o = response.json()
print()
and here an example of json file...
{
"time": {
"updated": "Aug 16, 2022 18:13:00 UTC",
"updatedISO": "2022-08-16T18:13:00 00:00",
"updateduk": "Aug 16, 2022 at 19:13 BST"
},
"disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"chartName": "Bitcoin",
"bpi": {
"USD": {
"code": "USD",
"symbol": "$",
"rate": "23,960.8828",
"description": "United States Dollar",
"rate_float": 23960.8828
},
"GBP": {
"code": "GBP",
"symbol": "£",
"rate": "20,021.5220",
"description": "British Pound Sterling",
"rate_float": 20021.522
},
"EUR": {
"code": "EUR",
"symbol": "€",
"rate": "23,341.3982",
"description": "Euro",
"rate_float": 23341.3982
}
}
}
CodePudding user response:
you can use the keys as indices.
o["bpi"]["USD"]["rate"]