json_format 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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.
  5. import argparse
  6. import json
  7. import os
  8. import sys
  9. def GetFormattedJSONString(file_path):
  10. with open(file_path, 'r') as f:
  11. json_obj = json.load(f)
  12. file_content = f.read()
  13. return json.dumps(
  14. json_obj, indent=2, sort_keys=True, separators=(',', ': '))
  15. def ValidateJSONFormat(file_path):
  16. with open(file_path, 'r') as f:
  17. file_content = f.read()
  18. if file_content != GetFormattedJSONString(file_path):
  19. raise Exception(
  20. 'Reformat your JSON file by running: %s --format %s' %
  21. (__file__, file_path))
  22. print >> sys.stdout, ('%s passes the JSON format validation' % file_path)
  23. def Format(file_path):
  24. formatted_JSON_string = GetFormattedJSONString(file_path)
  25. with open(file_path, 'w') as f:
  26. f.write(formatted_JSON_string)
  27. def Main(args):
  28. description = """A JSON formatting tool.
  29. This is a tool that validate and reformats JSON file so that it complies with
  30. a certain style. The JSON style imposed by this tool is:
  31. * JSON array elements and object members are indented with 2 spaces.
  32. * Dictionaries objects are sorted by key.
  33. * Items are sperated by ', ' and ': '.
  34. """
  35. parser = argparse.ArgumentParser(
  36. description=description, formatter_class=argparse.RawTextHelpFormatter)
  37. parser.add_argument('file_path', type=str, help='The path to JSON file.')
  38. parser.add_argument('--format', action='store_true', default=False,
  39. help='Format the JSON file.')
  40. options = parser.parse_args(args)
  41. if options.format:
  42. Format(options.file_path)
  43. return 0
  44. ValidateJSONFormat(options.file_path)
  45. return 0
  46. if __name__ == '__main__':
  47. sys.exit(Main(sys.argv[1:]))