[英]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.