Show all errors in json schema using json validate using python

Viewed 5919

I am writing a Python code to validate JSON schema but it is not showing all the errors in it , only the first one. Can anyone help to fix the code so that it displays all the errors. Below is the code:

from __future__ import print_function
import sys
import json
import jsonschema
from jsonschema import validate

schema = {
    "type" : "object",
    "properties" : {
        "price" : {"type" : "number"},
        "name" : {"type" : "string"},
    },
}

data = \
[
    { "name": 20, "price": 10},        
]

print("Validating the input data using jsonschema:")
for idx, item in enumerate(data):
    try:
        validate(item, schema)
        sys.stdout.write("Record #{}: OK\n".format(idx))
    except jsonschema.exceptions.ValidationError as ve:
        sys.stderr.write("Record #{}: ERROR\n".format(idx))
        sys.stderr.write(str(ve) + "\n")
2 Answers

To get all the validation errors in a single instance, use iter_errors() method of the validator class.

eg.:

import jsonschema

schema = {
    "type" : "object",
    "properties" : {
        "price" : {"type" : "number"},
        "name" : {"type" : "string"},
    },
}
data = { "name": 20, "price": "ten"}

validator = jsonschema.Draft7Validator(schema)

errors = validator.iter_errors(data)  # get all validation errors

for error in errors:
    print(error)
    print('------')

Output:

'ten' is not of type 'number'

Failed validating 'type' in schema['properties']['price']:
    {'type': 'number'}

On instance['price']:
    'ten'

------
20 is not of type 'string'

Failed validating 'type' in schema['properties']['name']:
    {'type': 'string'}

On instance['name']:
    20

------

The jsonschema.validate() method chooses the best match error among these by some heuristic and raises it.

You can add continue or pass in the except block to skip it from quiting after first exception.

Related