format-json 844 Bytes
Newer Older
1 2 3
#!/usr/bin/env python
r"""Command-line tool to format software release JSON for slapos.

4 5
Inspired by json.tool from python, but enforcing 2 spaces and non-sorted keys.
The files are modified in-place.
6 7 8

Usage::

9
    format-json file1.json [file2.json]
10 11 12

"""

13
from __future__ import print_function
14 15 16 17 18 19
import sys
import json
import collections


def main():
20
  exit_code = 0
21
  for f in sys.argv[1:]:
22 23
    print('Processing', f,)
    with open(f) as infile:
24 25 26
      try:
        obj = json.load(infile, object_pairs_hook=collections.OrderedDict)
      except ValueError as e:
27
        exit_code = 1
28
        print(e, file=sys.stderr)
29
      else:
30
        with open(f, 'w') as outfile:
31 32 33
          json.dump(obj, outfile, sort_keys=False, indent=2, separators=(',', ': '))
          outfile.write('\n')
  sys.exit(exit_code)
34 35 36

if __name__ == '__main__':
  main()