#!/usr/bin/env python3 # Prettify input json file: indent, sort import sys import argparse import json parser = argparse.ArgumentParser() parser.add_argument("--nosort", action='store_true', help="Don't sort the output", default=False) parser.add_argument("--clobber",action='store_true', help="Overwrite the input file", default=False) parser.add_argument("--indent", type=int, help="Indentation to use for the output file (default 1)", default=1) parser.add_argument("file", help="Input file(s) - omit to use as filter", nargs='*') args = parser.parse_args() sorted = "unsorted" if args.nosort else "sorted" python2 = (sys.hexversion < 0x030000F0) # Any files provided? if len(args.file) > 0: if python2: print("Using Python2 (adds trailing spaces), output will be " + sorted + ". Indent = " + str(args.indent)) else: print("Using Python3 (strips trailing spaces), output will be " + sorted + ". Indent = " + str(args.indent)) sort_keys = not args.nosort def dump(input, file): json.dump(input, file, indent=args.indent, sort_keys=sort_keys, ensure_ascii=False) for arg in args.file: print("Reading " + arg) input = {} try: with open(arg, "rb") as f: input = json.loads(f.read().decode('UTF-8', errors='replace')) out = arg if args.clobber else arg + ".out" print("Writing " + out) if python2: with open(out, "w") as f: dump(input, f) else: with open(out, "w", encoding='utf-8') as f: dump(input, f) # we catch exception so can continue to process other files except Exception as ex: print(ex) # No input files provided, work as filter if len(args.file) == 0: try: input = json.loads(sys.stdin.buffer.read().decode('UTF-8', errors='replace')) except AttributeError: input = json.loads(sys.stdin.read().decode('UTF-8', errors='replace')) dump(input, sys.stdout)