Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show all errors in json schema using json validate using python

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")
like image 905
Anand Naidu Avatar asked Sep 06 '18 04:09

Anand Naidu


People also ask

How do you validate a JSON file against a schema?

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.

Can we validate JSON with schema?

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.

How do you validate a JSON string in Python?

You can try to do json. loads() , which will throw a ValueError if the string you pass can't be decoded as JSON.


1 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.

like image 51
Nitin Labhishetty Avatar answered Oct 07 '22 08:10

Nitin Labhishetty