如何在 json 模式的帮助下验证 json?
How to validate json with help of jsonschema?
我想验证我的 json 输入 -- my_json
。我预计会有异常(因为 job1 不是 job.
如何验证这个 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 架构文档 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
我想验证我的 json 输入 -- my_json
。我预计会有异常(因为 job1 不是 job.
如何验证这个 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 架构文档 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