Git/suuid/: New commits
[sunny256-utils.git] / jsonfmt.py
blob816ccb2430ce361bf908acdd1388e31a3d8f5702
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 """
13 def format_json(text, indent=2, sort=False):
14 """Return formatted JSON"""
15 import json
17 return json.dumps(
18 json.loads(text),
19 ensure_ascii=False,
20 indent=indent,
21 sort_keys=sort,
25 def main():
26 import argparse
27 import os
28 import sys
30 progname = os.path.basename(__file__)
32 parser = argparse.ArgumentParser(
33 description="JSON formatter",
35 parser.add_argument(
36 "-i",
37 "--indent",
38 default=2,
39 help="Use X spaces as indent",
40 metavar="X",
41 type=int,
43 parser.add_argument(
44 "-s",
45 "--sort",
46 action="store_true",
47 default=False,
48 help="Sort JSON elements alphabetically",
50 args = parser.parse_args()
52 try:
53 print(
54 format_json(
55 "".join(sys.stdin.readlines()),
56 indent=args.indent,
57 sort=args.sort,
60 except ValueError:
61 sys.stderr.write("%s: Invalid JSON\n" % progname)
64 if __name__ == "__main__":
65 main()