openmedialibrary_platform/Darwin/lib/python3.4/json/tool.py

40 lines
954 B
Python
Raw Normal View History

2013-10-11 17:28:32 +00:00
r"""Command-line tool to validate and pretty-print JSON
Usage::
$ echo '{"json":"obj"}' | python -m json.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
"""
import sys
import json
def main():
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
2014-09-30 16:15:32 +00:00
infile = open(sys.argv[1], 'r')
2013-10-11 17:28:32 +00:00
outfile = sys.stdout
elif len(sys.argv) == 3:
2014-09-30 16:15:32 +00:00
infile = open(sys.argv[1], 'r')
outfile = open(sys.argv[2], 'w')
2013-10-11 17:28:32 +00:00
else:
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
with infile:
try:
obj = json.load(infile)
2014-09-30 16:15:32 +00:00
except ValueError as e:
2013-10-11 17:28:32 +00:00
raise SystemExit(e)
with outfile:
2014-09-30 16:15:32 +00:00
json.dump(obj, outfile, sort_keys=True, indent=4)
2013-10-11 17:28:32 +00:00
outfile.write('\n')
if __name__ == '__main__':
main()