Home > OS >  Extract array name from JSON Python
Extract array name from JSON Python

Time:03-06

I am using Python to query an api containing country information found at https://restcountries.com/v3.1/all.

Using the Python script below I am able to iterate over all the objects and extract the name and the country code.

Python Script

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)

The above works fine for what I need so far, however I also need to extract the currency code for the country and the complication is that the value I need is actually the name of the array eg. "USD": {"name": "United States dollar","symbol": "$"} here I would like to be able to extract "USD".

Example 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"
  }
]

Any help is greatly appreciated

CodePudding user response:

In this case it might be helpful to use the .keys method on the sub dict currencies.

The issue with this is that for some list_items there is no 'currencies' key in which case there is no name to extract. Also in some cases there are more than one!

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