check-jsonschema.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import json
  2. from jsonschema import Draft7Validator
  3. from json_source_map import calculate
  4. from json_source_map.errors import InvalidInputError
  5. import os
  6. import sys
  7. errors = []
  8. def main():
  9. if len(sys.argv) < 2:
  10. print("JSON path required.")
  11. return 1
  12. for filename in sys.argv[1:]:
  13. prep(filename)
  14. try:
  15. with open('validation_errors.json', 'w') as outfile:
  16. json.dump(errors, outfile)
  17. except OSError as e:
  18. print(f'Failed to write validation output to file: {e}')
  19. return 1
  20. if errors:
  21. return 1
  22. return 0
  23. def prep(filename):
  24. try:
  25. with open(filename) as json_file:
  26. json_string = json_file.read()
  27. json_data = json.loads(json_string)
  28. except OSError as e:
  29. print(f'Failed to load file "{filename}": {e}')
  30. return
  31. schema_filename = json_data.get('$schema')
  32. if not schema_filename:
  33. print('File has no schema:', filename)
  34. return
  35. file_path = os.path.split(filename)[0]
  36. schema_file = os.path.join(file_path, schema_filename)
  37. try:
  38. with open(schema_file) as json_file:
  39. schema = json.load(json_file)
  40. except OSError as e:
  41. print(f'Failed to load schema file "{schema_file}": {e}')
  42. return
  43. validate(filename, json_data, json_string, schema)
  44. def validate(filename, json_data, json_string, schema):
  45. try:
  46. servicesPaths = calculate(json_string)
  47. except InvalidInputError as e:
  48. print("Error with file:", e)
  49. return
  50. cls = Draft7Validator(schema)
  51. for e in sorted(cls.iter_errors(json_data), key=str):
  52. print(f'{e}\nIn "{filename}"\n\n')
  53. errorPath = '/'.join(str(v) for v in e.absolute_path)
  54. errorEntry = servicesPaths['/' + errorPath]
  55. errors.append({
  56. "file": filename,
  57. "start_line": errorEntry.value_start.line + 1,
  58. "end_line": errorEntry.value_end.line + 1,
  59. "title": "Validation Error",
  60. "message": e.message,
  61. "annotation_level": "failure"
  62. })
  63. if __name__ == '__main__':
  64. sys.exit(main())