-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
jsonfmt.py
43 lines (32 loc) · 888 Bytes
/
jsonfmt.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
#!/usr/bin/env python
from __future__ import print_function
from jsoncomment import JsonComment
from jsonschema import validate
import json
import os
import sys
def decode(s):
for encoding in 'utf-8-sig', 'utf-16':
try:
return s.decode(encoding)
except UnicodeDecodeError:
continue
return s.decode('latin-1')
def touch(filename, mtime):
with open(filename, 'a+'):
pass
os.utime(filename, (mtime, mtime))
return 0
file = sys.argv[1]
print('Updating', file)
mtime = os.path.getmtime(file)
with open(file, 'rb') as f:
jstr = f.read(os.path.getsize(file))
jstr_no_bom = decode(jstr)
parser = JsonComment(json)
json_data = parser.loads(jstr_no_bom)
new_data = json.dumps(json_data, sort_keys=True, indent=4, separators=(',', ': '))
with open(file, 'wb') as f:
f.write(new_data+"\n")
touch(file, mtime)
sys.exit(0)