【发布时间】:2021-02-09 16:05:55
【问题描述】:
我是 JSON 新手,如果我错过了一些非常简单的东西,我不会感到惊讶,但是我尝试并未能找到我在架构中到底做错了什么以及为什么它错误地验证了某些事情。 这是我的架构:
apartment_schema = {
"type": "object",
"properties": {
"Apartments": {"type": "object"},
"properties": {"ap1": {"type": "object",
"required": ["count", "ages"],
"properties": {"count": {"type": "number"},
"ages": {"type": "array", "items": {"type": "number"}}},
"additionalProperties": False,
},
"ap2": {"type": "object",
"required": ["count", "ages"],
"properties": {"count": {"type": "number"},
"ages": {"type": "array", "items": {"type": "number"}}},
"additionalProperties": False,
},
"ap3": {"type": "object",
"required": ["count", "ages"],
"properties": {"count": {"type": "number"},
"ages": {"type": "array", "items": {"type": "number"}}},
"additionalProperties": False,
},
},
"required": ["ap1", "ap2", "ap3"],
"additionalProperties": False,
},
"additionalProperties": False,
"required": ["Apartments"]
}
我正在尝试使用 json.loads 验证字符串,然后针对此架构使用 validate 函数,但是当我尝试此操作时,我收到以下消息:
jsonschema.exceptions.SchemaError: ['ap1', 'ap2', 'ap3'] is not of type 'object', 'boolean'
这是我尝试验证它的方法,以及针对什么:
def validateJson(jsonData):
try:
jsonschema.validate(instance=jsonData, schema=apartment_schema)
except jsonschema.exceptions.ValidationError:
return False
return True
print(validateJson(json.loads("{\"Apartments\": {\"ap1\": {\"count\": 1, \"ages\": [40]},\"ap3\": {\"ages\": [10,15]}}}"))
此验证通过,如果我只从架构中删除一个必需的部分,即使它不应该通过,我也不会收到错误消息,因为它缺少一个必需的参数(计数)。当我输入不同的字符串时,似乎其他“必需”字段似乎都没有工作,即使它们没有引发错误。 我在这里做错了什么?
【问题讨论】:
标签: python json jsonschema