如何在jsonschema的帮助下验证json



我想验证我的json输入——my_json。我预期会出现异常(因为作业1不是作业。

如何验证这个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

您正确地进行了测试,但架构是错误的。架构应该是这样的。你可以在这里查看json模式文档

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

相关内容

  • 没有找到相关文章

最新更新