JSONSchema所需的属性不起作用

2024-10-02 20:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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]}}}"))

这个验证通过了,如果我只是从模式中删除了一个必需的部分,我不会得到错误消息,即使它不应该通过,因为它缺少一个必需的参数(count)。当我输入不同的字符串时,其他“必需”字段似乎都不起作用,即使它们没有引起错误。 我在这里做错了什么


Tags: falsenumberobjectschematypecount模式required
1条回答
网友
1楼 · 发布于 2024-10-02 20:30:54

在“公寓”属性声明的正下方有一个额外的properties关键字,该关键字不应该存在,因此下面的所有内容都在错误的级别被解析。我想您是想让物业“ap1”、“ap2”和“ap3”在数据中与“公寓”处于同一水平

相关问题 更多 >