format_json.py 726 Bytes
Newer Older
Mathieu Giraud's avatar
Mathieu Giraud committed
1
from __future__ import print_function
2
3
4
5
import json
import sys
from collections import OrderedDict

6
7
8
9
10
11
12
13
14
15
import argparse

parser = argparse.ArgumentParser(description = 'Format a .json file')
parser.add_argument('--unsorted', '-u', action='store_true', help='do not sort the file (%(default)s)')
parser.add_argument('--one-line', '-1', action='store_true', help='one line output (%(default)d)')
parser.add_argument('file', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help='.json file')

args = parser.parse_args()
json_data = args.file.read()

Mathieu Giraud's avatar
Mathieu Giraud committed
16
print(json.dumps(json.loads(json_data, object_pairs_hook=OrderedDict),
17
                 sort_keys=not args.unsorted,
Mathieu Giraud's avatar
Mathieu Giraud committed
18
                 indent=None if args.one_line else 2))
19
20