Python: Save JSON String to CSV File

In this tutorial, we will use an example to show how to save json string to a csv file.

Python - Save JSON String to CSV File - a step guide

1.Import library

import csv

2.Prepare json string in python

cols = ['Name', 'Age', 'Gender'] 

data = [ 
{'Name': 'John', 'Age': '20', 'Gender': 'Male'}, 
{'Name': 'James', 'Age': '28', 'Gender': 'Male'},     
{'Name': 'Cardi', 'Age': '25', 'Gender': 'Female'} 
]

3.Save json to csv file

path = "C:/Users/HP/OneDrive/Desktop/DEMO.csv"
with open(path, 'w') as f: 
    wr = csv.DictWriter(f, fieldnames = cols) 
    wr.writeheader() 
    wr.writerows(data)

Run this code, you may see this result:

Python: Save JSON String to CSV File