jsonschema 不验证缺少的必需属性

jsonschema not validating missing required properties

我知道这个问题经常出现,我在发布之前尝试研究这个问题,但仍然不知道我错过了什么

我有一个包含嵌套对象的架构。我的模式期望 company 属性 成为一个对象。该对象上有必需的属性,但它们被忽略了。为什么它忽略了必需的属性?

架构:

{
        'business_type': {
            'type': 'string',
            "enum": ['company', 'non_profit']
        },
        'email': {
            'type': 'string'
        },
        'company': {
            'type': 'object',
            'properties': {
                'address': {
                    'type': 'object',
                    'properties': {
                        'city': {
                            'type': 'string',
                        },
                        'country': {
                            'type': 'string',
                            'enum': ['US']
                        },
                        'line1': {
                            'type': 'string'
                        },
                        'line2': {
                            'type': 'string'
                        },
                        'postal_code': {
                            'type': 'string'
                        },
                        'state': {
                            'type': 'string'
                        }
                    },
                    'required': ['city', 'country', 'line1', 'postal_code', 'state'],
                },
                'name': {
                    'type': 'string'
                },
                'phone': {
                    'type': 'string'
                }
            },
            'required': ['address', 'name', 'phone'],
        },
        'required' : ['business_type', 'email', 'company']
    }

没有失败但应该失败的示例对象,因为它缺少 phone 属性

{
    "business_type": "company",
    "email": "email@email.com",
    "company": {
        "address": {
            "city": "city",
            "country": "US",
            "line1": "line1",
            "line2": "line2",
            "postal_code": "00000",
            "state": "AZ"
        },
        "name": "name"
    }
}

如果缺少 business_type、电子邮件或公司,验证工作正常,因此它不会验证嵌套结构。

我假设我忽略了一些东西,我只是不知道我忽略了什么

您需要将 business_typeemailcompany 包装在 properties 关键字中。否则模式不会将它们视为属性,只是模式中的额外数据。 JSON 架构将忽略它不知道的关键字。

你在 company 子模式中是正确的。