0

Im iterating through a nested json tree with Pandas dataframe. The issue im having is more or less simple to solve, but im out of ideas. When im traversing trough the nested json tree i get to a part where i cant get out of it and continue on another branch (i.e. when i reach Placeholder 1 i cant return and continue with Placeholder 2 (see json below). Here is my code so far:

def recursiveImport(df):
    for row,_ in enumerate(df):
        # Get ID, Name, Type
        id = df['ID'].values[row]
        name = df['Name'].values[row]
        type = df['Type'].values[row]
        
        # Iterate through Value
        if type == 'struct':
            for i in df.at[row, 'Value']:
                df = pd.json_normalize(i)
                recursiveImport(df)
        elif type != 'struct':
            value = df['Value'].values[row]
            print(f'Value: {value}')
            return
data = pd.read_json('work_gmt.json', orient='records')
print(data)
recursiveImport(data)

And the (minified) data im using for this is below (you can use a online json viewer to get a better look):

[{"ID":11,"Name":"Data","Type":"struct","Value":[[{"ID":0,"Name":"humidity","Type":"u32","Value":0},{"ID":0,"Name":"meta","Type":"struct","Value":[{"ID":0,"Name":"height","Type":"e32","Value":[0,0]},{"ID":0,"Name":"voltage","Type":"u16","Value":0},{"ID":0,"Name":"Placeholder 1","Type":"u16","Value":0}]},{"ID":0,"Name":"Placeholder 2","Type":"struct","Value":[{"ID":0,"Name":"volume","Type":"struct","Value":[{"ID":0,"Name":"volume profile","Type":"struct","Value":[{"ID":0,"Name":"upper","Type":"u8","Value":0},{"ID":0,"Name":"middle","Type":"u8","Value":0},{"ID":0,"Name":"down","Type":"u8","Value":0}]}]}]}]]}]

I tried using an indexed approach and keep track of each branch, but that didn't work for me. Perhaps i have to use a Stack/Queue to keep track? Thanks in advance! Cheers!

Tom
  • 37
  • 8

0 Answers0