How to convert a JSON file to CSV — PYTHON SCRIPT

Gabriel Pires
Dec 13, 2016 · 1 min read

Hi everybody, this is a simple snippet to help you convert your JSON file to a CSV file using a Python script.

Create a new Python file like: json_to_csv.py

Add this code:

import csv, json, sys
#if you are not using utf-8 files, remove the next line
sys.setdefaultencoding("UTF-8") #set the encode to utf8
#check if you pass the input file and output file
if sys.argv[1] is not None and sys.argv[2] is not None:
fileInput = sys.argv[1]
fileOutput = sys.argv[2]
inputFile = open(fileInput) #open json file
outputFile = open(fileOutput, 'w') #load csv file
data = json.load(inputFile) #load json content
inputFile.close() #close the input file
output = csv.writer(outputFile) #create a csv.write output.writerow(data[0].keys()) # header row for row in data:
output.writerow(row.values()) #values row

After adding this, save the file and run at the terminal:

python json_to_csv.py input.txt output.csv

If you have any doubt, feel free to contact me at Twitter @gabrielpires or by e-mail eu at gabrielpires.com.br

SEEYA!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store