I am trying to parse json data from a site that shows values of crypto currency. I am trying to parse it using python. I am a little lost on how to show the output.
API: https://min-api.cryptocompare.com/data/price?fsym=XMR&tsyms=USD
# code starts below
import requests
# Set the request parameters
url = 'https://min-api.cryptocompare.com/data/price?fsym=XMR&tsyms=USD'
# Fetch url
print("Fetching url..")
# Do the HTTP get request
response = requests.get(url, verify=True) #Verify is check SSL certificate
# Error handling
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
# Decode the JSON response into a dictionary and use the data
USD = response.json()
output = USD[0]['USD']
print('Output USD:'), USD
# code ends
I am getting a response code 200 because IDLE tries to exit. The code is based off another project and I don't believe I am parsing json correctly?
2 Answers 2
The problem is here:
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
The way you've indented, Python will always call exit(). You want it to call exit() only if there was actually an error, like so:
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
However, you have another problem. You're trying to assign "output" the value of an object in USD; USD doesn't exist:
data = response.json()
output = USD[0]['USD'] #"USD" doesn't exist. It's the value you're trying to find, not the json that contains the object itself.
print('Output USD:'), USD #"USD" doesn't exist. I think you meant to print "output" here, which is the value you're setting in the line above.
Instead, try this:
data = response.json()
output = data["USD"]
print('Output USD:'), output
2 Comments
Your exit() line is not indented correctly. Try this:
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
Additionally, even though you are parsing the JSON correctly, you incorrectly use the resulting data. Try this:
output = USD['USD'] # Note: "[0]" not required
print('Output USD:', USD) # Note: ", USD" inside the parentheses