'How to convert CSV to multi level nested JSON in Python

How to convert CSV to nested JSON in Python This is related to something like this.

I want to convert a flat dataframe file to Nested JSON format:

I have a csv (sales_2020) file in the following format:

enter image description here

and i want a json like this:

enter image description here

i tried the link above and was able to add 1 level using this:

import pandas as pd

df = pd.read_csv('your_file.csv')

df['sales_2020'] = df[['computer','mobile']].to_dict('records')

out = df[['a','Sales_2020']].to_json(orient='records', indent=4)

But i was unable to add 1 more level to it..i.e sales for a specific month..I tried this below solution but doesnt work..

df['jan']['sales_2020'] =df[['computer','mobile']].to_dict('records')

please help me out



Solution 1:[1]

I guess what you want is orient='index'

df['sales_2020'] = df[['computer','mobile']].to_dict('records')
out = df.set_index('Month')[['sales_2020']].to_json(orient='index', indent=4)
{
    "jan":{
        "sales_2020":{
            "computer":10,
            "mobile":5
        }
    },
    "feb":{
        "sales_2020":{
            "computer":8,
            "mobile":2
        }
    },
    "march":{
        "sales_2020":{
            "computer":6,
            "mobile":12
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ynjxsjmh