-3

I have a json file which looks like:

{
    "ancestors": [
        {
            "subcategory": [
                {
                    "key": "city",
                    "name": "City"
                }
            ],
            "name": "Da Lat"
        },
        {
            "subcategory": [
                {
                    "key": "province",
                    "name": "Province"
                }
            ],
            "name": "Lam Dong Province"
        },
        {
            "subcategory": [
                {
                    "key": "country",
                    "name": "Country"
                }
            ],
            "name": "Vietnam"
        }
    ],
}

The problem is that I need to access the name of that subcategory whose key is province.

Here i want to access "Lam Dong Province"

I cant figure out how to go up one level and check the conditions.

jpp
  • 159,742
  • 34
  • 281
  • 339
Nishant Sah
  • 141
  • 3
  • 13

2 Answers2

2

Iterate over it, check for the condition you want. If the condition is true, return the value you want.

def search_subcategories(json_dict):
    for element in json_dict['ancestors']:
        if element['subcategory'][0]['key'] == 'province':
             return element['name']
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
2

You can use next with a generator comprehension.

res = next(i['name'] for i in json_dict['ancestors'] if
           i['subcategory'][0]['key'] == 'province')

# 'Lam Dong Province'

To construct the condition i['subcategory'][0]['key'], you need only note:

  1. Lists are denoted by [] and the only element of a list may be retrieved via [0].
  2. Dictionaries are denoted by {} and values may be retrieved via [key].
jpp
  • 159,742
  • 34
  • 281
  • 339