Skip to content

Instantly share code, notes, and snippets.

@Epicpkmn11
Last active April 21, 2022 21:28
Show Gist options
  • Save Epicpkmn11/325a26dc1f51972d65538f2d38d2b4d7 to your computer and use it in GitHub Desktop.
Save Epicpkmn11/325a26dc1f51972d65538f2d38d2b4d7 to your computer and use it in GitHub Desktop.
json2csv.py - Converts a JSON to a CSV
#!/usr/bin/env python3
"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
"""
import argparse
import csv
import json
parser = argparse.ArgumentParser(description="Converts a JSON to a CSV")
parser.add_argument("input", metavar="input.json", type=str, help="JSON file")
parser.add_argument("output", metavar="output.csv", type=str, help="CSV file")
parser.add_argument("columns", metavar="a,b,c", type=str, help="Columns, comma separated")
args = parser.parse_args()
with open(args.input, "r") as file:
j = json.loads(file.read())
with open(args.output, "w") as file:
columns = args.columns.split(",")
colDefaults = {}
for i, col in enumerate(columns):
colVal = col.split("=")
if(len(colVal) == 2):
columns[i] = colVal[0]
if(colVal[1][0] == '"'):
colVal[1] = colVal[1][1:]
if(colVal[1][-1] == '"'):
colVal[1] = colVal[1][:-1]
colDefaults[columns[i]] = colVal[1]
else:
colDefaults[col] = None
writer = csv.writer(file)
writer.writerow(columns)
for item in j:
row = []
valid = True
for col in columns:
if col in item or colDefaults[col] is not None:
row.append(item[col] if col in item else colDefaults[col])
else:
valid = False
print("Warning: %s does not have all the needed columns (missing %s)" % (item["title"], col))
break
if not valid:
continue
writer.writerow(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment