Search code examples
pythonjsonjsonschemajson-schema-validator

Need Detailed Error in json schema validation Python


I have below json schema, i want to use python's library to validate the input json against given schema, it's using draft-08 version i.e., 2019-09. so i tried using below code for the same but it does not gives error in detail, for ex. in provided sample input resending is of type boolean so it should give error as this is not of type boolean but instead code gives error as <[{'entityType': 'default', 'function': '01', 'resending': 'False', 'afdDefinitionName': 'example', 'originalMessageId': '12345'}] does not contain items matching the given schema>

schema:

{
    "$schema": "http://json-schema.org/draft/2019-09/schema#",
    "description": "my schema",
    "definitions": {
      "BCCI": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "entityType": {
            "description": "",
            "type": "string",
            "const": "default"
          },
          "function": {
            "description": "",
            "codelistName": "ADNFUN",
            "type": "string",
            "oneOf": [
              {
                "const": "01"
              },
              {
                "const": "02"
              },
              {
                "const": "09"
              },
              {
                "const": "54"
              }
            ]
          },
          "resending": {
            "description": "",
            "type": "boolean"
          },
          "afdDefinitionName": {
            "description": "",
            "customDescription": "",
            "type": "string"
          },
          "originalMessageId": {
            "description": "",
            "customDescription": "",
            "type": "string"
          }
        },
        "required": [
          "entityType",
          "function",
          "afdDefinitionName"
        ]
      }
    },
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "BCCI": {
        "type": "array",
        "uniqueItems": true,
        "allOf": [
          {
            "minContains": 1,
            "maxContains": 1,
            "contains": {
              "$ref": "#/definitions/BCCI"
            }
          }
        ]
      }
    },
    "required": [
      "BCCI"
    ]
  }

json Input:

{
    "BCCI": [
        {
            "entityType": "default",
            "function": "01",
            "resending": "false",
            "afdDefinitionName": "example",
            "originalMessageId": "12345"
        }
    ]
}

Code used:

import json
import jsonschema
from jsonschema import validate, validators, Draft7Validator, Draft201909Validator, Draft202012Validator
from jsonschema.exceptions import ValidationError

json_file = 'path to json instance'
json_schema_file = 'path to json schema instance'

with open(json_file) as f:
    document = json.load(f)

with open(json_schema_file) as f:
    schema = json.load(f)

errors = []
try:
    validate(instance=document, schema=schema)
except jsonschema.exceptions.ValidationError as e:
    print("----------------------------------------------------------")
    print(e)
    print("----------------------------------------------------------")
    
    print(f"Error message: {e.message}")
    print(f"Error tag: {e.json_path}")
    print(f"Error tag: {list(e.path)}")
    print(f"Definition: {e.validator}")

output:

----------------------------------------------------------
[{'entityType': 'default', 'function': '01', 'resending': 'false', 'afdDefinitionName': 'example', 'originalMessageId': '12345'}] does not contain items matching the given schema

Failed validating 'contains' in schema['properties']['BCCI']['allOf'][0]:
    {'contains': {'$ref': '#/definitions/BCCI'},
     'maxContains': 1,
     'minContains': 1}

On instance['BCCI']:
    [{'afdDefinitionName': 'example',
      'entityType': 'default',
      'function': '01',
      'originalMessageId': '12345',
      'resending': 'false'}]
----------------------------------------------------------
Error message: [{'entityType': 'default', 'function': '01', 'resending': 'false', 'afdDefinitionName': 'example', 'originalMessageId': '12345'}] does not contain items matching the given schema
Error tag: $.BCCI
Error tag: ['BCCI']
Definition: contains

it should have printed about boolean issue, or if there was any other issue with input json but it does not gives error in detail.


Solution

  • Issue was with the keywords being used in draft-08 version that is why it was not giving proper detailed error, please use Items/minItems/maxItems instead of contains/minContains/maxContains in your schema then your code will work, below is the updated code which i am using which gives error in detail for all the errors for one particular json instance.

    import json
    from jsonschema import  Draft201909Validator
    
    json_file = 'test.json'
    json_schema_file = 'test_schema.json'
    
    with open(json_file) as f:
        document = json.load(f)
    
    with open(json_schema_file) as f:
        schema = json.load(f)
    
    v = Draft201909Validator(schema)
    
    for rec in document:
        temp = rec.get("error", [])
        errors = sorted(v.iter_errors(rec), key=lambda e: e.path)
        for error in errors:
            print("---------------------------------------")
            print("json_path list:", list(error.path))
            print("error_message:", error.message)
            

    updated json input schema:

    {
        "$schema": "http://json-schema.org/draft/2019-09/schema#",
        "description": "my schema",
        "definitions": {
          "BCCI": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "entityType": {
                "description": "",
                "type": "string",
                "const": "default"
              },
              "function": {
                "description": "",
                "codelistName": "XXXXXX",
                "type": "string",
                "oneOf": [
                  {
                    "const": "01"
                  },
                  {
                    "const": "02"
                  },
                  {
                    "const": "09"
                  },
                  {
                    "const": "54"
                  }
                ]
              },
              "resending": {
                "description": "",
                "type": "boolean"
              },
              "afdDefinitionName": {
                "description": "",
                "customDescription": "",
                "type": "string"
              },
              "originalMessageId": {
                "description": "",
                "customDescription": "",
                "type": "string"
              }
            },
            "required": [
              "entityType",
              "function",
              "afdDefinitionName"
            ]
          }
        },
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "BCCI": {
            "type": "array",
            "uniqueItems": true,
            "items": {
                "$ref": "#/definitions/BCCI"
              },
              "minItems": 1,
              "maxItems": 1
          }
        },
        "required": [
          "BCCI"
        ]
      }