Skip to content

Instantly share code, notes, and snippets.

@davesque
Created June 19, 2018 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davesque/60ec6127b0cffa61d5f20087988b0e10 to your computer and use it in GitHub Desktop.
Save davesque/60ec6127b0cffa61d5f20087988b0e10 to your computer and use it in GitHub Desktop.
A little script for manipulating JSON
#!/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