Created
June 19, 2018 21:13
-
-
Save davesque/60ec6127b0cffa61d5f20087988b0e10 to your computer and use it in GitHub Desktop.
A little script for manipulating JSON
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
#!/usr/bin/env python3 | |
import argparse | |
import json | |
import sys | |
parser = argparse.ArgumentParser(description='Manipulate JSON documents.') | |
parser.add_argument( | |
'-i', '--indent', | |
metavar='N', | |
type=int, | |
default=2, | |
help='the number of spaces to use for indentation if not minifying', | |
) | |
parser.add_argument( | |
'-m', '--minify', | |
action='store_true', | |
help='minify the JSON document', | |
) | |
parser.add_argument( | |
'-s', '--sort-keys', | |
action='store_true', | |
help='sort keys in the JSON document', | |
) | |
parser.add_argument( | |
'-c', '--colorize', | |
action='store_true', | |
help='colorizes the JSON document', | |
) | |
args = parser.parse_args() | |
obj = json.load(sys.stdin) | |
if args.minify: | |
out = json.dumps(obj, separators=(',', ':'), sort_keys=args.sort_keys) | |
else: | |
out = json.dumps(obj, indent=args.indent, sort_keys=args.sort_keys) + '\n' | |
if args.colorize: | |
try: | |
from pygments import highlight | |
from pygments.lexers import JsonLexer | |
from pygments.formatters import TerminalFormatter | |
except ImportError: | |
sys.stderr.write('You must install the `pygments` library: pip install pygments\n') | |
sys.exit(1) | |
out = highlight(out, JsonLexer(), TerminalFormatter()) | |
sys.stdout.write(out) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment