-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathprettyjson.py
executable file
·45 lines (38 loc) · 1.06 KB
/
prettyjson.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python3
"""
A very basic solution to prettify a JSON file.
Usage:
prettyjson.py ugly.json
A better way is to use jq at https://stedolan.github.io/jq/ .
Usage of jq:
cat ugly.json | jq
"""
import json
import sys
from pathlib import Path
def beautify(fname):
"""
Beautify the content of the file and return it as a string.
"""
try:
with open(fname) as f:
d = json.load(f)
except FileNotFoundError:
print("Error: cannot open the input file.", file=sys.stderr)
exit(1)
except json.decoder.JSONDecodeError as e:
print("Error: there is something wrong with this file.", file=sys.stderr)
print(e, file=sys.stderr)
exit(1)
#
return json.dumps(d, indent=2)
##############################################################################
if __name__ == "__main__":
try:
fname = sys.argv[1]
except IndexError:
p = Path(sys.argv[0])
print("Usage: {} ugly.json".format(p.name), file=sys.stderr)
exit(1)
#
print(beautify(fname))