使用JSON模式进行验证时,它不是递归验证子实体吗?

时间:2019-03-06 21:54:36

标签: jsonschema

使用以下架构时

{
    "$schema": "http://json-schema.org/schema#",
    "definitions":{
        "entity": {
            "type": "object",
            "properties": {
                "parent": {"type": ["null","string"]},
                "exclude": {"type": "boolean"},
                "count": {"type": ["null","integer"]},
                "EntityType": {"type": "string"},
                "Children": {
                    "type": "array",
                    "items": {"$ref":"#/definitions/entity"}
                }
            }
        }
    },
    "required": ["parent","EntityType","count"]
}

在提供的JSON正文上

{
    "parent": "null",
    "EntityType": "test",
    "count": "null",
    "Children": [
        {
            "EntityType": "test",
            "count": 3
        },
        {
            "EntityType": "test"
        }
    ],
    "Extra": "somevalue"
}

应该返回的是我提供了一个无效的Json对象,但是似乎没有这样做。

也就是说,如果我要使根节点不成功(通过除去必填字段之一),则验证有效,并说我没有提供必填字段。是否有我无法递归验证json的原因?

1 个答案:

答案 0 :(得分:2)

您似乎希望parentEntityTypecountentity定义的必需属性。但是,仅在根目录才需要它们,而不是entity级别。我建议您将required关键字移到entity定义中,然后将定义作为allOf的一部分引用,以确保根目录符合要求。

{
    "$schema": "http://json-schema.org/schema#",
    "definitions":{
        "entity": {
            "type": "object",
            "properties": {
                "parent": {"type": ["null","string"]},
                "exclude": {"type": "boolean"},
                "count": {"type": ["null","integer"]},
                "EntityType": {"type": "string"},
                "Children": {
                    "type": "array",
                    "items": {"$ref":"#/definitions/entity"}
                }
            },
            "required": ["parent","EntityType","count"]
        }
    },
    "allOf": [{"$ref": "#/definitions/entity"}]
}