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")
                The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.
JSON Schema is a powerful tool. It enables you to validate your JSON structure and make sure it meets the required API. You can create a schema as complex and nested as you need, all you need are the requirements. You can add it to your code as an additional test or in run-time.
You can try to do json. loads() , which will throw a ValueError if the string you pass can't be decoded as JSON.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With