Skip to content

Instantly share code, notes, and snippets.

@the-sofi-uwu
Created January 7, 2021 23:05
Show Gist options
  • Save the-sofi-uwu/590b18e144eeaf2fd1feb2834fef18d3 to your computer and use it in GitHub Desktop.
Save the-sofi-uwu/590b18e144eeaf2fd1feb2834fef18d3 to your computer and use it in GitHub Desktop.
NESTED JSON to CSV in Python
import copy
import json
def flat_json(data, last_name = "", rows = [{}], keys = []):
last_row = rows[len(rows)-1]
if type(data) is dict:
lists = {}
for key in data:
name = last_name + ("__" if last_name else "") + key
if type(data[key]) is list:
lists[key] = data
else:
value = flat_json(data[key], name, rows, keys)
if value != None:
last_row[name] = value
if not name in keys:
keys.append(name)
for key in lists:
name = last_name + ("__" if last_name else "") + key
flat_json(data[key], name, rows, keys)
elif type(data) is list:
if len(data) > 0:
flat_json(data[0], last_name, rows, keys)
for idx in range(1, len(data)):
rows.append(copy.deepcopy(last_row))
flat_json(data[idx], last_name, rows, keys)
else:
return data
def json_to_csv(data):
out = [{}]
keys = []
flat_json(data, "", out, keys)
out_str = ",".join(map(lambda x: '"'+x+'"',keys)) + "\n"
for row in out:
row_str = ""
for key in keys:
if key in row:
row_str += ',"' + str(row[key]) + '"'
else:
row_str += ',""'
out_str += row_str[1:] + "\n"
return out_str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment