jpayne@69: r"""Command-line tool to validate and pretty-print JSON jpayne@69: jpayne@69: Usage:: jpayne@69: jpayne@69: $ echo '{"json":"obj"}' | python -m json.tool jpayne@69: { jpayne@69: "json": "obj" jpayne@69: } jpayne@69: $ echo '{ 1.2:3.4}' | python -m json.tool jpayne@69: Expecting property name enclosed in double quotes: line 1 column 3 (char 2) jpayne@69: jpayne@69: """ jpayne@69: import argparse jpayne@69: import json jpayne@69: import sys jpayne@69: jpayne@69: jpayne@69: def main(): jpayne@69: prog = 'python -m json.tool' jpayne@69: description = ('A simple command line interface for json module ' jpayne@69: 'to validate and pretty-print JSON objects.') jpayne@69: parser = argparse.ArgumentParser(prog=prog, description=description) jpayne@69: parser.add_argument('infile', nargs='?', jpayne@69: type=argparse.FileType(encoding="utf-8"), jpayne@69: help='a JSON file to be validated or pretty-printed', jpayne@69: default=sys.stdin) jpayne@69: parser.add_argument('outfile', nargs='?', jpayne@69: type=argparse.FileType('w', encoding="utf-8"), jpayne@69: help='write the output of infile to outfile', jpayne@69: default=sys.stdout) jpayne@69: parser.add_argument('--sort-keys', action='store_true', default=False, jpayne@69: help='sort the output of dictionaries alphabetically by key') jpayne@69: parser.add_argument('--json-lines', action='store_true', default=False, jpayne@69: help='parse input using the jsonlines format') jpayne@69: options = parser.parse_args() jpayne@69: jpayne@69: infile = options.infile jpayne@69: outfile = options.outfile jpayne@69: sort_keys = options.sort_keys jpayne@69: json_lines = options.json_lines jpayne@69: with infile, outfile: jpayne@69: try: jpayne@69: if json_lines: jpayne@69: objs = (json.loads(line) for line in infile) jpayne@69: else: jpayne@69: objs = (json.load(infile), ) jpayne@69: for obj in objs: jpayne@69: json.dump(obj, outfile, sort_keys=sort_keys, indent=4) jpayne@69: outfile.write('\n') jpayne@69: except ValueError as e: jpayne@69: raise SystemExit(e) jpayne@69: jpayne@69: jpayne@69: if __name__ == '__main__': jpayne@69: main()