October 06, 2020

Convert JSON file to CSV with Python

 Hi folks,

Today I will explain the code to implement the Json2CSV conversion.

Make sure you have valid JSON file with an array of objects.

Sample:

"Users":[

{"id": 1, "Name": "Suresh Raju", "Age": 35},

{"id":2, "Name": "PSR", "Age": 34}

]

I have chosen Python language to convert because of inbuilt library support for json and csv and command line execution with Notepad++ as editor.

Source Code Snippet: GitHub Gist

Please send your valuable feedback and comments to psrdotcom@gmail.com


import json
import csv
# Read JSON File
with open('users.json') as json_file:
data = json.load(json_file)
user_data = data['users']
# Prepare CSV file
data_file = open('users.csv', 'w')
# Make CSV file writer
csv_writer = csv.writer(data_file)
count = 0
for tmp in user_data:
if count == 0:
# Add headers to CSV file
header = tmp.keys()
csv_writer.writerow(header)
count += 1
# Write data to CSV file
csv_writer.writerow(tmp.values())
# Close the CSV file
data_file.close()
view raw json2csv.py hosted with ❤ by GitHub

No comments:

Featured Post

Java Introdcution

Please send your review and feedback to psrdotcom@gmail.com