Blame view

format-json 810 Bytes
Jérome Perrin committed
1 2 3
#!/usr/bin/env python
r"""Command-line tool to format software release JSON for slapos.

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

Usage::

Jérome Perrin committed
9
    format-json file1.json [file2.json]
Jérome Perrin committed
10 11 12 13 14 15 16 17 18 19

"""

import os
import sys
import json
import collections


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

if __name__ == '__main__':
  main()