Home > Software design >  How to validate json with help of jsonschema?
How to validate json with help of jsonschema?

Time:12-21

I want to validate my json input -- my_json. I expected exception (because job1 is not job.

How to validate this json?

import json
from jsonschema import validate

# Describe what kind of json you expect.
schema = {
    "job" : {"type" : "string"},
    "big_list": [
    {
        "id": 1,
        "code": "qqq"
    },
    {
        "id": 2,
        "code": ""
    }
    # many items
    ]
}

# Convert json to python object.
my_json = {'job1': "as", 'big_list': [{'id': 1, 'code': 'qqq'}, {'id': 2, 'code': ''}]}
validate(instance=my_json, schema=schema) # I expected exception, but have no exceptions

CodePudding user response:

You did the test correctly but the schema is wrong. Schema should be like this. You can check the json schema docs here

import json
from jsonschema import validate

# Describe what kind of json you expect.
schema = {
    "type" : "object",
    "properties" : 
    {
        "job" : {"type" : "string"},
        "big_list" : {"type" : "object"},
     }
}

# Convert json to python object.
my_json = {'job1': "as", 'big_list': [{'id': 1, 'code': 'qqq'}, {'id': 2, 'code': ''}]}
valid_json = {'job1': "as", 'big_list': {'id': 1, 'code': 'qqq'}}
validate(instance=valid_json, schema=schema) # 
print('valid json has passed')
validate(instance=my_json, schema=schema) # this should raise an error
  • Related