Skip to content

Instantly share code, notes, and snippets.

@cbonesana
Last active June 22, 2022 16:51
Show Gist options
  • Save cbonesana/db8b4902c12d52508f057e71fd116d85 to your computer and use it in GitHub Desktop.
Save cbonesana/db8b4902c12d52508f057e71fd116d85 to your computer and use it in GitHub Desktop.
Basic Python script that merge and beautify multiple JSONs files in subfolders. Given an input folder, it scans the directory tree, merging together the JSONs file found in a file in the parent folder called "<folder>-output.json". This script has one only CLI argument, i.e. "python beautify-json.py <root-folder>"
import json
import os
import sys
encoding = 'utf-8'
indentNum = 4
def clean(data):
return json.dumps(data, sort_keys=True, indent=indentNum, separators=(',', ': '))
walk_dir = sys.argv[1]
print (walk_dir)
abs_dir = os.path.abspath(walk_dir)
print('walk_dir = ' + abs_dir)
for root, subdirs, files in os.walk(abs_dir):
if (root.startswith('.')):
continue
dirname = os.path.basename(root)
output_file = os.path.join(os.path.join(root, os.pardir), dirname +'-output.json')
print('--\nfolder = ' + root)
print('output file = ' + output_file)
out = []
for filename in files:
if (filename.endswith('-output.json')):
continue
file_path = os.path.join(root, filename)
if filename.endswith('.json'):
print('\t- file ' + filename)
with open(file_path, 'r', encoding=encoding) as f:
data = f.read()
content = json.loads(data)
out.append(content)
clean_content = clean(out)
with open(output_file, 'wb+') as out_file:
out_file.write(clean_content.encode(encoding))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment