Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to access nested JSON elements in Python's request reponse

I’ve been trying to call an API GET request to get a list of countries from an online sim provider. I’m trying to get the list of all the countries and to access certains elements from it.

The result of the request is such as :

{
   "afghanistan": {
      "iso": {
         "af": 1
      },
      "prefix": {
         "+93": 1
      },
      "text_en": "Afghanistan",
      "text_ru": "Афганистан",
      [...]
   "albania": {
      [...]
}

My issue that I can’t find a proper way to loop over the array (afghanistan, albania, […]) and to access the text_en key.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Out of everything that I have tried, this is (not working) what I think should work, according to examples / people’s issues I found online :

countries = requests.get("(api_link)").json()

for country in countries:
    print(country['text_en'])

giving me the following error : TypeError: string indices must be integers

As my array is not named like most of the examples I found online (the root of the array is named for example list and the code look like :

for country in countries['list']:
    print(country['list']['text_en'])

Why can’t I do it like my first example ? The thing I thought about is that my JSON isn’t properly loaded (hence the TypeError: string indices must be integers), the way I loop over the array (for i in X or by using a JSON function?) or maybe because of the "issue" mentionned above (not having a "root" array name) ?

>Solution :

countries is a dictionary. for country in countries therefore loops over the keys in the dictionary, and if you try country['text_en'], you’re trying to index the first key (a string) with another string, which won’t work.

Something like countries['afghanistan']['text_en'] would evaluate to 'Afghanistan'.

To print all of them:

for key, data in countries.items():
    print(key, data['text_en'])

This works because it loops over items, which yields tuples of key and value from the dictionary.

Another approach, closer to what you expected:

for key in countries:
    print(key, countries[key]['text_en'])

That may be a bit less efficient, because you need to look up every element using its key one at a time, while the first loop accesses all of them in order, but code that’s readable is worth something too – at the very least, perhaps it helps to see how the dictionary works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading