使用 Python 解析深度(多个)嵌套的 JSON 块 3.6.8
Parsing deeply (multiple) nested JSON blocks with Python 3.6.8
我见过几个相关的“Python 中嵌套 json”的问题,但是这种冠状病毒 JSON 数据的语法给我带来了问题。这是一个示例:
{"recovered":524855,"list":[
{"countrycode":"US","country":"United States of America","state":"South Carolina","latitude":"34.22333378","longitude":"-82.46170658","confirmed":15228,"deaths":568},
{"countrycode":"US","country":"United States of America","state":"Louisiana","latitude":"30.2950649","longitude":"-92.41419698","confirmed":43612,"deaths":2957}
]}
如果我只想去路易斯安那州,这就是我的尝试:
import json
import requests
url = "https://covid19-data.p.api.com/us"
headers = {
'x-api-key': "<api-key>",
'x-api-host': "covid19-data.p.api.com"
}
response = requests.request("GET", url, headers=headers)
coronastats = json.loads(response.text)
la_deaths = coronastats["list"][0]["countrycode"]["US"]["country"]["United States of America"]["state"]["Louisiana"]["deaths"]
print("Value: %s" % la_deaths)
我得到:“类型错误:字符串索引必须是整数”
这显然是一个列表(我是一名侦探并推断出一个名为“list”的变量可能是一个列表)但是长键值列表让我失望(我认为)。
问题是一旦你得到了列表的第一个元素,你就只剩下一个深度为一的字典。数据并不像您想象的那样嵌套。您很快就会找到一个字符串,然后尝试使用 US
字符串对其进行索引,这会引发异常。
In [2]: data
Out[2]:
{'recovered': 524855,
'list': [{'countrycode': 'US',
'country': 'United States of America',
'state': 'South Carolina',
'latitude': '34.22333378',
'longitude': '-82.46170658',
'confirmed': 15228,
'deaths': 568},
{'countrycode': 'US',
'country': 'United States of America',
'state': 'Louisiana',
'latitude': '30.2950649',
'longitude': '-92.41419698',
'confirmed': 43612,
'deaths': 2957}]}
In [3]: data["list"][0]
Out[3]:
{'countrycode': 'US',
'country': 'United States of America',
'state': 'South Carolina',
'latitude': '34.22333378',
'longitude': '-82.46170658',
'confirmed': 15228,
'deaths': 568}
In [7]: data["list"][0]["countrycode"]
Out[7]: 'US'
In [8]: type(data["list"][0]["countrycode"])
Out[8]: str
In [9]: data["list"][0]["countrycode"]["asdf"]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-cb9dbc39ef82> in <module>
----> 1 data["list"][0]["countrycode"]["asdf"]
TypeError: string indices must be integers
要到达特定国家/地区,您要做的是在列表中找到该州,例如使用代码:
In [14]: [f"{row['state']}: {row['deaths']} deaths. Wear a mask!" for row in data["list"] if row["state"] == "Louisiana"]
Out[14]: ['Louisiana: 2957 deaths. Wear a mask!']
您还可以使用 filter
、pandas
和一百万种其他解决方案来对 table.
进行排序
试试这个:
coronastats = json.loads(response.text)
[coronastats["list"][i]["deaths"] for i in range(len(coronastats["list"])) if coronastats["list"][i]["state"] == "Louisiana"]
我见过几个相关的“Python 中嵌套 json”的问题,但是这种冠状病毒 JSON 数据的语法给我带来了问题。这是一个示例:
{"recovered":524855,"list":[
{"countrycode":"US","country":"United States of America","state":"South Carolina","latitude":"34.22333378","longitude":"-82.46170658","confirmed":15228,"deaths":568},
{"countrycode":"US","country":"United States of America","state":"Louisiana","latitude":"30.2950649","longitude":"-92.41419698","confirmed":43612,"deaths":2957}
]}
如果我只想去路易斯安那州,这就是我的尝试:
import json
import requests
url = "https://covid19-data.p.api.com/us"
headers = {
'x-api-key': "<api-key>",
'x-api-host': "covid19-data.p.api.com"
}
response = requests.request("GET", url, headers=headers)
coronastats = json.loads(response.text)
la_deaths = coronastats["list"][0]["countrycode"]["US"]["country"]["United States of America"]["state"]["Louisiana"]["deaths"]
print("Value: %s" % la_deaths)
我得到:“类型错误:字符串索引必须是整数”
这显然是一个列表(我是一名侦探并推断出一个名为“list”的变量可能是一个列表)但是长键值列表让我失望(我认为)。
问题是一旦你得到了列表的第一个元素,你就只剩下一个深度为一的字典。数据并不像您想象的那样嵌套。您很快就会找到一个字符串,然后尝试使用 US
字符串对其进行索引,这会引发异常。
In [2]: data
Out[2]:
{'recovered': 524855,
'list': [{'countrycode': 'US',
'country': 'United States of America',
'state': 'South Carolina',
'latitude': '34.22333378',
'longitude': '-82.46170658',
'confirmed': 15228,
'deaths': 568},
{'countrycode': 'US',
'country': 'United States of America',
'state': 'Louisiana',
'latitude': '30.2950649',
'longitude': '-92.41419698',
'confirmed': 43612,
'deaths': 2957}]}
In [3]: data["list"][0]
Out[3]:
{'countrycode': 'US',
'country': 'United States of America',
'state': 'South Carolina',
'latitude': '34.22333378',
'longitude': '-82.46170658',
'confirmed': 15228,
'deaths': 568}
In [7]: data["list"][0]["countrycode"]
Out[7]: 'US'
In [8]: type(data["list"][0]["countrycode"])
Out[8]: str
In [9]: data["list"][0]["countrycode"]["asdf"]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-cb9dbc39ef82> in <module>
----> 1 data["list"][0]["countrycode"]["asdf"]
TypeError: string indices must be integers
要到达特定国家/地区,您要做的是在列表中找到该州,例如使用代码:
In [14]: [f"{row['state']}: {row['deaths']} deaths. Wear a mask!" for row in data["list"] if row["state"] == "Louisiana"]
Out[14]: ['Louisiana: 2957 deaths. Wear a mask!']
您还可以使用 filter
、pandas
和一百万种其他解决方案来对 table.
试试这个:
coronastats = json.loads(response.text)
[coronastats["list"][i]["deaths"] for i in range(len(coronastats["list"])) if coronastats["list"][i]["state"] == "Louisiana"]