我正在使用 Python 查詢包含在https://restcountries.com/v3.1/all找到的國家/地區資訊的 api 。
使用下面的 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"
}
]
任何幫助是極大的贊賞
uj5u.com熱心網友回復:
.keys在這種情況下,對 sub dict 貨幣使用該方法可能會有所幫助。
這樣做的問題是,對于某些 list_items 沒有“貨幣”鍵,在這種情況下沒有要提取的名稱。在某些情況下還有不止一個!
for list_item in json_list:
name = list_item["name"]["common"]
currency_keys = list(list_item.get('currencies', {}).keys())
print(name)
print(currency_keys)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438175.html
