堆栈溢出和python都很新,所以如果格式错误,我很抱歉。不确定是否有必要,但我正在使用 VS Code。
我从 covid-19 rapid api 中提取数据,它输出数据(json),但没有给我实际需要的数据:
这是拉它的代码:
import requests
url = "https://covid-19-data.p.rapidapi.com/report/country/code"
querystring = {"date":"2020-04-01","code":"it"}
headers = { 'x-rapidapi-host': "covid-19-data.p.rapidapi.com", 'x-rapidapi-key': "SIGN-UP-FOR-KEY" }
response = requests.request("GET", url, headers=headers, params=querystring) print(response.text)
一旦我得到它,它就会输出:
[{"country":"USA","provinces":[{"province":"USA"}],"latitude":37.09024,"longitude":-95.712891,"date":"2022-01-24"}]
但是,在快速 api 网站上,它在“示例响应”下显示我需要的数据(死亡、恢复、活动等)嵌套在 [{"province":"USA"}] 部分下:
[1 item
0:{5 items
"country":"Italy"
"provinces":[1 item
0:{5 items
"province":"Italy"
"confirmed":110574
"recovered":16847
"deaths":13155
"active":80572
}
]
"latitude":41.87194
"longitude":12.56738
"date":"2020-04-01"
}
]
我想从该嵌套字典中提取数据,但我不确定如何。这是我的尝试,但没有奏效,只是想显示数据:
import requests
import json
def get_covid_data_19(country_code, date):
'''
This function gets COVID 19 data via rapid API. This takes two parameters:
Country Name (string) and Date (YYYY-MM-DD)
'''
c = country_code
d = date
# Endpoint that we are going to be hitting:
url = "https://covid-19-data.p.rapidapi.com/report/country/code"
querystring = {"code" : c, "date" : d}
headers = {
'x-rapidapi-host': "covid-19-data.p.rapidapi.com",
'x-rapidapi-key': "insertkeyhere"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.json()
data = []
for response in json_data:
data.append ({
'confirmed' : response.get('confirmed'),
'recovered' : response.get('recovered'),
'deaths' : response.get('deaths'),
'active' : response.get('active'),
'date' : response.get('date'),
})
print(data)
我还尝试以 xml 格式检索数据,但也不知道如何扩展数组。任何建议都会很棒。谢谢。