【问题标题】:JSON:TypeError: string indices must be integersJSON:TypeError: 字符串索引必须是整数
【发布时间】:2020-08-09 09:56:00
【问题描述】:

我正在尝试从 here 获取全球确诊病例总数,但是当我尝试运行此功能时得到 TypeError: string indices must be integers

def getstats():
    api_url = urllib.request.urlopen('https://api.covid19api.com/summary')
    data = json.load(api_url)
    for item in data["Global"]:
        print(item["TotalConfirmed"])

【问题讨论】:

    标签: json python-3.x python-requests iteration


    【解决方案1】:

    itemString 下的 Global 键。使用print(item) 查看字符串。您需要进一步解析该字符串以获取 TotalConfirmed 值。

    【讨论】:

      【解决方案2】:

      遍历data["Global"] 中的项目会将键作为字符串返回。

      print(*(i for i in data["Global"]))
      
      NewConfirmed TotalConfirmed NewDeaths TotalDeaths NewRecovered TotalRecovered
      

      您要做的是获取内部字典的值

      print(data["Global"]["TotalConfirmed"])
      
      2807945
      

      【讨论】:

        猜你喜欢
        • 2020-08-28
        • 2019-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-06
        • 1970-01-01
        相关资源
        最近更新 更多