Skip to content

Instantly share code, notes, and snippets.

@maurobaraldi
Last active August 29, 2015 14:10
Show Gist options
  • Save maurobaraldi/7562d11c5bec8b519cee to your computer and use it in GitHub Desktop.
Save maurobaraldi/7562d11c5bec8b519cee to your computer and use it in GitHub Desktop.
JSON prettifier and uglifier console
#!/usr/bin/env python
import argparse
from json import load, loads, dump, dumps
from StringIO import StringIO
parser = argparse.ArgumentParser(description='JSON console tools')
parser.add_argument('-v', '--validate', action='store_true', help='validate JSON data')
parser.add_argument('-l', '--inline', action='store_true', help='uglify JSON data')
parser.add_argument('-p', '--prettify', action='store_true', help='prettify JSON data')
parser.add_argument('-f', '--file', nargs=1, type=str, required=True, help='Input file (required)')
args = parser.parse_args()
def _file_(path):
with open(path, 'rb') as fp:
return StringIO(fp.read())
def inline(path, encoding=None):
''' Convert a JSON data to inline.'''
try:
print dumps(load(_file_(path), encoding=encoding))
except ValueError:
print 'JSON object could not be decoded'
def prettify(path, encoding=None, spaces=2):
''' Prettify a JSON data.'''
try:
print dumps(load(_file_(path), encoding=None), indent=spaces)
except ValueError:
print 'JSON object could not be decoded'
def validate(data):
try:
loads(data)
print True
except ValueError:
print False
if args.validate: validate(args.validate[0])
elif args.inline: inline(args.file[0])
elif args.prettify: prettify(args.file[0])
else: parser.print_help()
@maurobaraldi
Copy link
Author

Install & Usage

Install

sudo wget https://gist.githubusercontent.com/maurobaraldi/7562d11c5bec8b519cee/raw/02aa60d0fc91a06350d2188f15cb4ee0411435a0/jsontools -O /usr/bin/jsontools

sudo chmod +x /usr/bin/jsontools

Usage

jsontools -h

JSON console tools

optional arguments:
-h, --help show this help message and exit
-v VALIDATE, --validate VALIDATE
validate JSON data
-l, --inline uglify JSON data
-p, --prettify prettify JSON data
-f FILE, --file FILE Input file (required)

_Preetify a JSON file_

jsontools -f /path/to/file.json -p

_Uglify (inline) a JSON file_

jsontools -f /path/to/file.json -l

_Validate a JSON file_

jsontools -f /path/to/file.json -v

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment