0

My goal is to identify which instanse is dict, str or list under the items hierarchy.

def flatten(data):
    for i, item in enumerate(data['_embedded']['items']):
        if isinstance(item, dict):
            print('Item', i, 'is a dict')
        elif isinstance(item, list):
            print('Item', i, 'is a list')
        elif isinstance(item, str):
            print('Item', i, 'is a str')
        else:
            print('Item', i, 'is unknown')
flatten(data)

Output of this code is:

Item 0 is a dict
Item 1 is a dict
Item 2 is a dict
Item 3 is a dict
Item 4 is a dict

Desired out put should access the keys (identifier, enabled,family) inside the 0, 1 etc.

for a better udnerstnading of the structure of the JSON file please see the image enter image description here

Greencolor
  • 501
  • 1
  • 5
  • 16
  • You need a nested for-loop or some kind of recursion to inspect the dictionaries. – Michael Butscher Jan 14 '23 at 17:45
  • yeah I tried to something liek this to reach lower level `def flatten (data): for element in data['_embedded']: for element['items'] in element: print(element['items']) flatten(data)` but getting error `'str' object does not support item assignment` – Greencolor Jan 14 '23 at 17:47
  • If "value" is a dict, you can just iterate over its keys or items with an additional for-loop in the if-block. Something like `for element['items'] in element` usually doesn't make sense. – Michael Butscher Jan 14 '23 at 17:52

1 Answers1

0

It seems like you want to recursively print the type of every field. To do that, you can simply call the function again in the case the object you find is a dictionnary. It would look like :

def flatten(data):
    for key, value in data['_embedded']['items']:
        if isinstance(value, dict):
            print(key + ' is dict')
            flatten(value)
        [...]

This way you will keep entering nested dictionnaries and displaying them just as you did for the outer one.

PoneyUHC
  • 287
  • 1
  • 11