'Parsing nested json to csv using pandas python

I want to convert JSON to CSV.

Below is JSON file

{
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "topping":
        [
            { "t_id": "5001", "top_type": "None" },
            { "t_id": "5002", "top_type": "Glazed" }
        ]
}

Below is code which I have written:

import csv, json
import pandas as pd
 
f = open(r'C:\Desktop\test.json',encoding='utf-8')  
data = json.load(f)

df = pd.json_normalize(data).to_csv(r'C:\Desktop\test.csv',encoding='utf-8',index=False)

I am getting this output:

id,type,name,ppu,topping,t_id,top_type
1,donut,Cake,0.55,"[{'t_id': '5001', 'top_type': 'None'}, {'t_id': '5002', 'top_type': 'Glazed'}]","['5001',5002']","['None','Glazed']"

Desired Output:

id,type,name,ppu,topping,t_id,top_type
1,donut,Cake,0.55,[{'t_id': '5001', 'top_type': 'None'}, {'t_id': '5002', 'top_type': 'Glazed'}],['5001',5002'],['None','Glazed']


Sources

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

Source: Stack Overflow

Solution Source