-2

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

1 Answer 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
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.