【发布时间】:2021-03-06 17:04:13
【问题描述】:
这是通过询问用户一个输入而成功运行的代码,在这种情况下是状态
import requests
import simplejson as json
response = requests.get("https://api.covidtracking.com/v1/states/ca/daily.json")
json_test = response.json()
print("Enter the state for which the COVID data should be retrieved (e.g. TX): ")
user_state = input()
count = 0
for i in json_test:
i = count
count = count + 1
state = (json_test[i]['state'])
dates = (json_test[i]['date'])
if state == user_state:
death = (json_test[i]['death'])
print("State: " + str(state))
print("Date: " + str(dates))
print("Death(s)" + str(death))
print("===============")
输出将类似于:
Date: 20201112
Death(s)18108
===============
State: CA
Date: 20201111
Death(s)18070
===============
State: CA
Date: 20201110
Death(s)18001
===============
State: CA
Date: 20201109
Death(s)17977
===============
但我正在尝试实现用户在命令行上输入美国州和日期的选项,例如:
Enter the state for which the COVID data should be retrieved (e.g. TX): CA
Enter the date for which the COVID data should be retrieved (e.g. 20201219): 20210219
我试过的代码是:
import requests
import simplejson as json
response = requests.get("https://api.covidtracking.com/v1/states/ca/daily.json")
json_test = response.json()
print("Enter the state for which the COVID data should be retrieved (e.g. TX): ")
user_state = input()
print("Enter the date for which the COVID data should be retrieved (e.g. 20201219): ")
user_date = input()
count = 0
for i in json_test:
i = count
count = count + 1
state = (json_test[i]['state'])
dates = (json_test[i]['date'])
if state == user_state and dates == user_date:
death = (json_test[i]['death'])
print("State: " + str(state))
print("Date: " + str(dates))
print("Death(s)" + str(death))
print("===============")
但是,我的输出没有结果,但也没有错误。我现在知道为什么它不起作用了
【问题讨论】:
-
我看到 JSON 中的日期是整数,例如
20210305,而不是字符串。您可以尝试将用户输入转换为 int 或处理日期。
标签: python json for-loop parsing