Json flattening python

119 Views Asked by At

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

1

There are 1 best solutions below

0
PoneyUHC On

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.