std/python: Add missing trailing comma + `make format`
[sunny256-utils.git] / jsonfmt.py
blob4c9f2b954206796891399805545a916966d6c63a
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
4 """jsonfmt.py - JSON formatter
6 File ID: 423dd854-4a64-11e4-97b1-c80aa9e67bbd
7 License: GNU General Public License version 2 or later.
8 Author: Øyvind A. Holm <sunny@sunbase.org>
10 """
12 def format_json(text, indent=4):
13 """Return formatted JSON"""
14 import json
16 return json.dumps(
17 json.loads(text),
18 ensure_ascii=False,
19 indent=indent,
20 sort_keys=True,
23 def main():
24 import argparse
25 import os
26 import sys
28 progname = os.path.basename(__file__)
30 parser = argparse.ArgumentParser(
31 description='JSON formatter',
33 parser.add_argument(
34 '-i', '--indent',
35 default=2,
36 help='Use X spaces as indent',
37 metavar='X',
38 type=int,
40 args = parser.parse_args()
42 try:
43 print(format_json(''.join(sys.stdin.readlines()),
44 indent=args.indent,
46 except ValueError:
47 sys.stderr.write("%s: Invalid JSON\n" % progname)
49 if __name__ == "__main__":
50 main()