Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
validation.py 1.21 KiB
import json
import jsonschema
from lofar.sas.tmss.tmss.exceptions import *

def validate_json_against_schema(json_string: str, schema: str):
    '''validate the given json_string against the given schema.
       If no exception if thrown, then the given json_string validates against the given schema.
       :raises SchemaValidationException if the json_string does not validate against the schema
     '''

    # ensure the given arguments are strings
    if type(json_string) != str:
        json_string = json.dumps(json_string)
    if type(schema) != str:
        schema = json.dumps(schema)

    # ensure the specification and schema are both valid json in the first place
    try:
        json_object = json.loads(json_string)
    except json.decoder.JSONDecodeError as e:
        raise SchemaValidationException("Invalid JSON: %s\n%s" % (str(e), json_string))

    try:
        schema_object = json.loads(schema)
    except json.decoder.JSONDecodeError as e:
        raise SchemaValidationException("Invalid JSON: %s\n%s" % (str(e), schema))

    # now do the actual validation
    try:
        jsonschema.validate(json_object, schema_object)
    except jsonschema.ValidationError as e:
        raise SchemaValidationException(str(e))