![](/img/trans.png)
[英]required and additionalProperties is not working for jsonschema module Python
[英]python jsonschema validation fails when additionalProperties is set to false
我正在尝试在 python 脚本中定义一个模式,以立即用于验证一些 json 数据。 架构定义如下所示:
response_schema = {
"required": ["identifiers" ],
"properties": {
"identifiers": {
"minProperties": 1,"maxProperties": 1,
"additionalProperties": {
"required": [ "name","surname" ],
"properties": {
"surname": {
"required": ["sur1", "sur2" ],
"properties": {
"sur1": { },
"sur2": { }
} },
"name": {},
"additionalProperties": false
}
}
}
},
"additionalProperties": false
}
该架构在任何在线验证器中都可以正常工作,但是当我在脚本中执行验证时:
validate(response_body_dict, response_schema)
我收到以下错误:
NameError: 名称 'false' 未定义
如果我从模式中删除"additionalProperties" : false
,我不会收到错误消息,但当然它对我不起作用,因为它是限制性较小的验证。
谁能解释为什么我收到这个错误?
问题在于 Python 和 JSON 之间的差异。 在 Python 中,您将其拼写为“False”,而在 JSON 中,您将其拼写为“false”。
如果您将架构复制到文本文件中并使用 json 模块加载它,它将正常工作 - 没有错误。
当您在 Python 程序中加载这段代码时,您会收到您提供的错误,因为 Python 不知道“false”是什么。 代码正在创建字典,而不是 JSON 模式。
如果你想就地原型,你可以将它包装在 """ 中,然后使用 json.loads。
像这样:
import json
response_schema_str = """{
"required": ["identifiers" ],
"properties": {
"identifiers": {
"minProperties": 1,
"maxProperties": 1,
"additionalProperties": {
"required": [
"name",
"surname" ],
"properties": {
"surname": {
"required": [
"sur1",
"sur2" ],
"properties": {
"sur1": { },
"sur2": { }
}
},
"name": {},
"additionalProperties": false
}
}
}
},
"additionalProperties": false
}"""
response_schema = json.loads(response_schema_str)
print(response_schema)
我在尝试针对 Python 脚本中的类似 JSON 模式进行验证时遇到了同样的错误。 由于 ChipJust 提供的原因,我将false
更改为False
,它对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.