tool.py 954 Bytes
Newer Older
1 2 3 4
r"""Command-line tool to validate and pretty-print JSON

Usage::

5
    $ echo '{"json":"obj"}' | python -m json.tool
6 7 8
    {
        "json": "obj"
    }
9
    $ echo '{ 1.2:3.4}' | python -m json.tool
10
    Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
11 12 13 14 15 16 17 18 19 20

"""
import sys
import json

def main():
    if len(sys.argv) == 1:
        infile = sys.stdin
        outfile = sys.stdout
    elif len(sys.argv) == 2:
21
        infile = open(sys.argv[1], 'r')
22 23
        outfile = sys.stdout
    elif len(sys.argv) == 3:
24 25
        infile = open(sys.argv[1], 'r')
        outfile = open(sys.argv[2], 'w')
26
    else:
27
        raise SystemExit(sys.argv[0] + " [infile [outfile]]")
28 29 30 31 32 33 34 35
    with infile:
        try:
            obj = json.load(infile)
        except ValueError as e:
            raise SystemExit(e)
    with outfile:
        json.dump(obj, outfile, sort_keys=True, indent=4)
        outfile.write('\n')
36 37 38 39


if __name__ == '__main__':
    main()