Skip to content

Instantly share code, notes, and snippets.

@sam2332
Created May 23, 2024 19:48
Show Gist options
  • Save sam2332/cabdfa06b35e9df355e017ec9feeb807 to your computer and use it in GitHub Desktop.
Save sam2332/cabdfa06b35e9df355e017ec9feeb807 to your computer and use it in GitHub Desktop.
Simple json conversion tool, reusable
# Description: This script converts a json file to a csv file
# Author: Lily Rudloff
# Date: 05-23-2024
# Version: 1.0
# Usage: python convert_to_csv.py input.json output.csv
# Notes: This script requires the json file to be a list of dictionaries
# where each dictionary represents a row in the csv file.
# The keys of the first dictionary will be used as the headers
# for the csv file.
#Import libraries
import json
import csv
#argparse input file and output file
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input", help="input json file")
parser.add_argument("output", help="output csv file")
args = parser.parse_args()
input_file = args.input
output_file = args.output
try:
with open(input_file) as json_file:
data = json.load(json_file)
except FileNotFoundError:
print("Error: Input file not found.")
exit(1)
except json.JSONDecodeError:
print("Error: Invalid JSON format in input file.")
exit(1)
try:
csv_file = open(output_file, 'w')
csv_writer = csv.writer(csv_file)
except IOError:
print("Error: Unable to open output file.")
exit(1)
try:
csv_writer.writerow(data[0].keys())
for page in data:
csv_writer.writerow(page.values())
except Exception as e:
print("Error: Failed to write data to CSV file.")
print(e)
finally:
csv_file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment