json模式具有
required
properties
和
required
字段。例如,
additionalProperties
将验证json对象,例如:{
"type": "object",
"properties": {
"elephant": {"type": "string"},
"giraffe": {"type": "string"},
"polarBear": {"type": "string"}
},
"required": [
"elephant",
"giraffe",
"polarBear"
],
"additionalProperties": false
}
但是,如果属性列表不是问题
我经常将{
"elephant": "Johnny",
"giraffe": "Jimmy",
"polarBear": "George"
}
列表复制到list列表,并且当列表因错别字和其他愚蠢的错误而匹配时会遇到烦人的错误。有一种较短的方法来表示所有属性都是必需的,而无需明确命名吗?
elephant, giraffe, polarBear
我怀疑是否有一种指定所需属性以外的其他属性的方法。 但是,如果您经常遇到此问题,我建议您编写一个小脚本,以后处理您的JSON-SCHEMA,并自动为所有定义的对象添加所需的数组。
脚本只需要穿越JSON-Schema树,在每个级别上,如果找到了“属性”关键字,请在同一级别的属性中添加一个“必需的”关键字。 让机器做钻孔。
例如,如果我想在db中使用required
{
"type": "object",
"properties": {
"elephant": {"type": "string"},
"giraffe": {"type": "string"},
"polarBear": {"type": "string"}
},
"additionalProperties": false,
"minProperties": 3
}
如果您在python中使用库jsonschema,请使用自定义验证器:
首先创建自定义验证器:
required
然后扩展了一个exits验证器:
现在测试:
update
您将收到错误:
prepareSchema(action) {
const actionSchema = R.clone(schema)
switch (action) {
case 'insert':
actionSchema.$id = `/${schema.$id}-Insert`
actionSchema.required = Object.keys(schema.properties)
return actionSchema
default:
return schema
}
}
您可以使用以下功能:# 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
)
如果您使用的是JavaScript,则可以使用
propertygetter.。
schema = {"allRequired": True}
instance = {"properties": {"name": {"type": "string"}}, "required": []}
v = customValidator(schema)
errors = validateInstance(v, instance)
其他人建议,以下是这样的后处理Python代码:
'name' should be required but only the following are required: []