Last active
May 5, 2022 00:09
-
-
Save javiervisiedo/9ba64d00dd02dff4add9c34d86daa850 to your computer and use it in GitHub Desktop.
Simple python script to format a json string sending the output to stdout or another file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import argparse | |
import sys | |
def format_json(input, output): | |
try: | |
with open(input, 'r') as ifile: | |
contents = json.load(ifile) | |
except IOError as e: | |
print(e) | |
sys.exit(1) | |
if output != None: | |
try: | |
with open(output, 'w') as ofile: | |
json.dump(contents, ofile, sort_keys=True, indent=2, separators=(',', ': ')) | |
except IOError as e: | |
print(e) | |
sys.exit(1) | |
else: | |
print (json.dumps(contents, sort_keys=True, indent=2, separators=(',', ': '))) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description='Format json file to make it easier to read for humans') | |
parser.add_argument('input_file', type=str, nargs=1) | |
parser.add_argument('output_file', type=str, nargs='?') | |
args = parser.parse_args() | |
ifile = args.input_file[0] | |
ofile = args.output_file if args.output_file != None else None | |
format_json(ifile, ofile) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment