import sys from jsonschema import validate, RefResolver, Draft202012Validator import json from pathlib import Path import logging import argparse # filename = sys.argv[1] # def load_json (path): # with open(path) as f: # s = json.load(f) # return s # schema_store = {} # json_instance = load_json(filename) # print (json_instance) # etsi_schema = load_json('response.schema.json') # ext_schema = load_json('extended.schema.json') # ext_ent_schema = load_json("extended_entities.schema.json") # schema_store = { # etsi_schema['$id'] : etsi_schema, # ext_schema['$id'] : ext_schema, # ext_ent_schema['$id'] : ext_ent_schema # } # resolver = RefResolver(None, referrer=None, store=schema_store) # print (etsi_schema) # v = Draft202012Validator(ext_schema, resolver=resolver) # v.validate(json_instance) # validate(json_instance, ext_schema) # print ("OK") def handle_uri(u): print(u) def load_json(path : str): with open(path) as f: return json.load(f) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-s','--schemadir', action="append", help="Directory containing supporting schema files to use for validation") parser.add_argument('-v', '--verbose', action="count", help="Verbose logging (can be specified multiple times)") parser.add_argument('schema', help="Primary schema to validate against") parser.add_argument('filename', help="JSON instance document to validate") args = parser.parse_args() match args.verbose: case v if v and v >= 2: logging.basicConfig(level=logging.DEBUG) case 1: logging.basicConfig(level=logging.INFO) case _: logging.basicConfig(level=logging.WARNING) logging.debug(f"Arguments: {args}") instance_doc = load_json(args.filename) main_schema = load_json(args.schema) schema_dict = { main_schema['$id'] : main_schema } if args.schemadir: schema_paths = [] for d in args.schemadir: schema_paths += [f for f in Path(d).rglob("*.schema.json")] logging.info(f"Schema files loaded: {schema_paths}") schemas_json = [json.load(p.open()) for p in schema_paths] schema_dict = schema_dict | { s['$id'] : s for s in schemas_json } logging.info(f"Schema IDs loaded: {[k for k in schema_dict.keys()]}") logging.debug (f"Instance doc: {instance_doc}") logging.debug (f"Main schema: {main_schema}") resolver = RefResolver(None, referrer=None, store=schema_dict) v = Draft202012Validator(main_schema, resolver=resolver) v.validate(instance_doc) logging.info("Done")