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