【发布时间】:2020-07-27 08:52:46
【问题描述】:
我在这样的文件中有一个draft-7JSON 架构:
{
"$schema": "http://json-schema.org/draft-07/schema",
"type": "object",
"required": [
"tenantid",
"owningObjectId",
"owningObject",
"cudAction",
"message"
],
"properties": {
"tenantid": {
"type": "string",
"default": ""
},
"owningObjectId": {
"type": "string",
"default": ""
},
"owningObject": {
"type": "string",
"default": "",
"pattern": "^TeamUser$"
},
"cudAction": {
"type": "string",
"default": "",
"pattern": "^c$"
},
"messageDateTime": {
"type": "string",
"default": ""
},
"encrypted": {
"type": "boolean",
"default": false
},
"message": {
"type": "array",
"items": {
"type": "object",
"required": [
"name",
"teamcode",
"enabled"
],
"properties": {
"name": {
"type": "string",
"default": ""
},
"teamcode": {
"type": "string",
"default": ""
},
"org": {
"type": "string",
"default": ""
},
"enabled": {
"type": "boolean",
"default": false,
},
"version": {
"type": "string",
"default": ""
},
"orgDisplay": {
"type": "string",
"default": ""
}
}
}
}
}
}
我正在使用以下架构验证 JSON/响应:
# pip install jsonschema
from jsonschema import Draft7validator
def validate_response(response, schema_file_path: str) -> bool:
"""
Validate the input message based on the input schema provided.
:reference http://json-schema.org/understanding-json-schema/
:param response: response received as JSON
:param schema_file_path: The schema file path
:return validated: returns True if valid response else False
"""
validated = True
with open(schema_file_path, "r") as schema_reader:
schema = json.loads(schema_reader.read())
errors = Draft7Validator(schema).iter_errors(response)
for error in errors:
print(error.message)
validated = False
if validated:
print(f"Valid response")
return validated
但是,对于像下面的 faulty_json_response 这样的 JSON,其中 message 字段值数组为空,并且 message 字段下不存在任何 required 属性,验证器不会抛出任何错误。可能是什么原因?
faulty_json_response = {
"tenantid": "5e3bb57222b49800016b666f",
"owningObjectId": "5e680018ceb7d600012e4375",
"owningObject": "TeamUser",
"cudAction": "c",
"messageDateTime": "1584460716.01416",
"encrypted": false,
"message": [],
}
如果需要更多详细信息,请告诉我。谢谢。
【问题讨论】:
标签: python json jsonschema json-schema-validator python-jsonschema