Skip to content Skip to sidebar Skip to footer

Convert Pandas DataFrame To Deeply Nested JSON With An Innermost Object Layer

Assume I have a DataFrame df like: source tables columns data_type length src1 table1 col1 INT 4 src1 table1 col2 CHAR

Solution 1:

def make_nested(df): 
    f = lambda: defaultdict(f)   
    data = f()  

    for row in df.to_numpy().tolist():
        t = data
        for r in row[:-3]:
            t = t[r]
        t[row[-3]] = {
            "type": row[-2],
            "length": row[-1]
        }

    return data

The last two column values go inside the third level, so thats what you should do.


Post a Comment for "Convert Pandas DataFrame To Deeply Nested JSON With An Innermost Object Layer"