我正在尝试从显示加密货币值的网站解析json数据。我试图使用python解析它。我对如何显示输出感到有点迷失。
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
我收到响应代码200,因为IDLE试图退出。该代码基于另一个项目,我不相信我正确解析json?
答案 0 :(得分:2)
问题在于:
newprice = row.replace("(","")
你缩进的方式,Python将始终调用exit()。你希望它只在实际出现错误时调用exit(),如下所示:
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
但是,您还有另一个问题。你试图用美元分配“输出”对象的值;美元不存在:
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
相反,试试这个:
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.
答案 1 :(得分:1)
您的exit()
行没有正确缩进。试试这个:
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
此外,即使您正确解析JSON,也会错误地使用结果数据。试试这个:
output = USD['USD'] # Note: "[0]" not required
print('Output USD:', USD) # Note: ", USD" inside the parentheses