简体   繁体   中英

Json flattening python

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在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM