JSON Schema - 需要所有属性

时间:2015-06-16 12:48:01

标签: jsonschema

JSON架构中的required字段

JSON Schema包含propertiesrequiredadditionalProperties字段。例如,

{
    "type": "object",
    "properties": {
        "elephant": {"type": "string"},
        "giraffe": {"type": "string"},
        "polarBear": {"type": "string"}
    },
    "required": [
        "elephant",
        "giraffe",
        "polarBear"
    ],
    "additionalProperties": false
}

将验证JSON对象,如:

{
    "elephant": "Johnny",
    "giraffe": "Jimmy",
    "polarBear": "George"
}

但如果属性列表不完全 elephant, giraffe, polarBear,则会失败。

问题

我经常将properties的列表复制粘贴到required列表中,并且由于拼写错误和其他愚蠢错误而导致列表不匹配时会遇到恼人的错误。

是否有更短的方式来表示所有属性都是必需的,而没有明确命名它们?

5 个答案:

答案 0 :(得分:29)

你可以使用" minProperties"属性而非明确命名所有字段。

{
    "type": "object",
    "properties": {
        "elephant": {"type": "string"},
        "giraffe": {"type": "string"},
        "polarBear": {"type": "string"}
    },
    "additionalProperties": false,
    "minProperties": 3
}

答案 1 :(得分:7)

我怀疑除了在必需的数组中明确命名它们之外,还有一种方法可以指定必需的属性。

但是如果你经常遇到这个问题,我建议你写一个小的脚本,对你的json-schema进行后处理,并自动为所有定义的对象添加所需的数组。

脚本只需要遍历json-schema树,并且在每个级别,如果找到“properties”关键字,添加一个“required”关键字,其中包含属性中包含的所有已定义键。

让机器完成钻孔。

答案 2 :(得分:0)

我在带有单行的代码中执行此操作,例如,如果我想在数据库中使用required作为insert,但只想在执行{{{{}}时对模式进行验证1}}。

update

答案 3 :(得分:0)

正如其他人所建议的,下面是这样的后处理python代码:

def schema_to_strict(schema):
    if schema['type'] not in ['object', 'array']:
        return schema

    if schema['type'] == 'array':
        schema['items'] = schema_to_strict(schema['items'])
        return schema

    for k, v in schema['properties'].items():
        schema['properties'][k] = schema_to_strict(v)

    schema['required'] = list(schema['properties'].keys())
    schema['additionalProperties'] = False
    return schema

答案 4 :(得分:0)

如果您在python中使用库jsonschema,请使用自定义验证程序:

首先创建自定义验证器:

# Custom validator for requiring all properties listed in the instance to be in the 'required' list of the instance
def allRequired(validator, allRequired, instance, schema):
    if not validator.is_type(instance, "object"):
        return
    if allRequired and "required" in instance:
        # requiring all properties to 'required'
        instanceRequired = instance["required"]
        instanceProperties = list(instance["properties"].keys())
        for property in instanceProperties:
            if property not in instanceRequired:
                yield ValidationError("%r should be required but only the following are required: %r" % (property, instanceRequired))
        for property in instanceRequired:
            if property not in instanceProperties:
                yield ValidationError("%r should be in properties but only the following are properties: %r" % (property, instanceProperties))

然后扩展现有的验证器:

all_validators = dict(Draft4Validator.VALIDATORS)
all_validators['allRequired'] = allRequired

customValidator = jsonschema.validators.extend(
    validator=Draft4Validator,
    validators=all_validators
)

现在测试:

schema =  {"allRequired": True}
instance = {"properties": {"name": {"type": "string"}}, "required": []}
v = customValidator(schema)
errors = validateInstance(v, instance)

您将收到错误: 'name' should be required but only the following are required: []

相关问题