从JSON Python中提取数组名称



我正在使用Python查询一个包含国家/地区信息的api,该信息位于https://restcountries.com/v3.1/all.

使用下面的Python脚本,我能够迭代所有对象并提取名称和国家代码。

Python脚本

import requests
import json
api_url = 'https://restcountries.com/v3.1/all'
response = requests.get(api_url)
json_list = response.json()
for list_item in json_list:
name = list_item["name"]["common"]
country_code = list_item["cca2"]
print(name)

到目前为止,以上内容适用于我所需要的内容,但我也需要提取国家的货币代码,复杂的是,我需要的值实际上是数组的名称,例如"USD": {"name": "United States dollar","symbol": "$"},我希望能够提取";美元";。

示例JSON

[
{
"name": {
"common": "United States",
"official": "United States of America",
"nativeName": {
"eng": {
"official": "United States of America",
"common": "United States"
}
}
},
"cca2": "US",
"currencies": {
"USD": {
"name": "United States dollar",
"symbol": "$"
}
},
"region": "Americas",
"subregion": "North America"
}
]

非常感谢任何帮助

在这种情况下,在子dict货币上使用.keys方法可能会有所帮助。

问题是,对于某些list_items,没有"currencies"键,在这种情况下,没有要提取的名称。在某些情况下还有不止一个!

for list_item in json_list:
name = list_item["name"]["common"]
currency_keys = list(list_item.get('currencies', {}).keys())
print(name)
print(currency_keys)

最新更新