Python - How To JSON to CSV in Python

ID : 233

viewed : 115

Tags : PythonPython JSONPython CSV

vote vote


JSON stands for JavaScript Object Notation. It is based on the format of objects in JavaScript and is an encoding technique for representing structured data. It is widely used these days, especially for sharing data between servers and web applications.

A CSV file is used for storing data in a tabular format like Excel Spreadsheets.

In this tutorial, we will learn how to convert JSON data to a CSV file.

Use the Pandas DataFrames to_csv() Method to Convert JSON to CSV in Python

In this method, we will first convert the JSON to a Pandas DataFrame and from there convert it to a CSV file using the to_csv() method. We can read the JSON string using the json.loads() function which is provided in the json library in Python to convert JSON to a DataFrame. Then we pass this JSON object to the json_normalize() function which will return a Pandas DataFrame containing the required data.

The following code snippet will explain how we do it.

import pandas as pd import json  data = ''' { "Results":          [          { "id": "1", "Name": "Jay" },          { "id": "2", "Name": "Mark" },          { "id": "3", "Name": "Jack" }          ], "status": ["ok"] } '''  info = json.loads(data)  df = pd.json_normalize(info['Results'])  df.to_csv("samplecsv.csv") 

The content of the created CSV file is below.

,id,Name 0,1,Jay 1,2,Mark 2,3,Jack 

Use the csv Module to Convert JSON to a CSV File

In this method, we will use the csv library in Python which is used for reading and writing CSV files. First, we will read the JSON data as we did in the previous method. We open a file in the write mode and use the DictWriter() from the csv module to creates an object which allows us to map and write JSON data to the file. The fieldnames are keys that are identified and matched with the data when we write rows using the writerows() function.

The following code snippet will show how we can implement the above method:

import csv import json  data = ''' { "Results":          [          { "id": "1", "Name": "Jay" },          { "id": "2", "Name": "Mark" },          { "id": "3", "Name": "Jack" }          ], "status": ["ok"] } '''  info = json.loads(data)['Results']  print(info[0].keys())  with open("samplecsv.csv", 'w') as f:      wr = csv.DictWriter(f, fieldnames = info[0].keys())      wr.writeheader()      wr.writerows(info)  

  • Related HOW TO?