1#!/usr/bin/env python
2# Copyright 2015 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5import argparse
6import json
7import os
8import sys
9
10
11def GetFormattedJSONString(file_path):
12 with open(file_path, 'r') as f:
13    json_obj = json.load(f)
14    file_content = f.read()
15 return json.dumps(
16     json_obj, indent=2, sort_keys=True, separators=(',', ': '))
17
18
19def ValidateJSONFormat(file_path):
20 with open(file_path, 'r') as f:
21    file_content = f.read()
22 if file_content != GetFormattedJSONString(file_path):
23   raise Exception(
24       'Reformat your JSON file by running: %s --format %s' %
25       (__file__, file_path))
26 print >> sys.stdout, ('%s passes the JSON format validation' % file_path)
27
28
29def Format(file_path):
30  formatted_JSON_string = GetFormattedJSONString(file_path)
31  with open(file_path, 'w') as f:
32    f.write(formatted_JSON_string)
33
34
35def Main(args):
36  description = """A JSON formatting tool.
37
38  This is a tool that validate and reformats JSON file so that it complies with
39  a certain style. The JSON style imposed by this tool is:
40    * JSON array elements and object members are indented with 2 spaces.
41    * Dictionaries objects are sorted by key.
42    * Items are sperated by ', ' and ': '.
43  """
44  parser = argparse.ArgumentParser(
45      description=description, formatter_class=argparse.RawTextHelpFormatter)
46  parser.add_argument('file_path', type=str, help='The path to JSON file.')
47  parser.add_argument('--format', action='store_true', default=False,
48                      help='Format the JSON file.')
49  options = parser.parse_args(args)
50  if options.format:
51    Format(options.file_path)
52    return 0
53  ValidateJSONFormat(options.file_path)
54  return 0
55
56
57if __name__ == '__main__':
58  sys.exit(Main(sys.argv[1:]))
59