如何定义至少需要一个属性的JSON模式
我想知道我是否可以定义一个JSON模式(草案4),它至少需要一个对象可能的属性中的一个。我已经知道了如何定义至少需要一个属性的JSON模式,json,jsonschema,Json,Jsonschema,我想知道我是否可以定义一个JSON模式(草案4),它至少需要一个对象可能的属性中的一个。我已经知道了allOf、anyOf和oneOf,但就是不知道如何以我想要的方式使用它们 以下是一些JSON示例: // Test Data 1 - Should pass { "email": "hello@example.com", "name": "John Doe" } // Test Data 2 - Should pass { "id": 1, "name": "J
allOf
、anyOf
和oneOf
,但就是不知道如何以我想要的方式使用它们
以下是一些JSON示例:
// Test Data 1 - Should pass
{
"email": "hello@example.com",
"name": "John Doe"
}
// Test Data 2 - Should pass
{
"id": 1,
"name": "Jane Doe"
}
// Test Data 3 - Should pass
{
"id": 1,
"email": "hello@example.com",
"name": "John Smith"
}
// Test Data 4 - Should fail, invalid email
{
"id": 1,
"email": "thisIsNotAnEmail",
"name": "John Smith"
}
// Test Data 5 - Should fail, missing one of required properties
{
"name": "John Doe"
}
我希望至少需要id
或email
(也接受两者),并且仍然根据格式通过验证。使用oneOf
验证失败,如果我同时提供了两者(测试3),anyOf
通过验证,即使其中一个无效(测试4)
这是我的模式:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "https://example.com",
"properties": {
"name": {
"type": "string"
}
},
"anyOf": [
{
"properties": {
"email": {
"type": "string",
"format": "email"
}
}
},
{
"properties": {
"id": {
"type": "integer"
}
}
}
]
}
您能帮助我如何为我的用例实现正确的验证吗?要要求至少一组属性中的一个,请在一系列
anyOf
选项中使用required
:
{
"type": "object",
"anyOf": [
{"required": ["id"]},
{"required": ["email"]}
// any other properties, in a similar way
],
"properties": {
// Your actual property definitions here
}
{
如果存在您想要的任何属性(
“id”
,“email”
),则它将传递中的相应选项。
这将缩短模式定义:
{
type: "object",
minProperties: 1,
properties: [/* your actual properties definitions */],
}
链接到文档:这实际上是一个糟糕的解决方案,因为如果对象不包含架构中定义的任何属性,而具有架构中不存在的属性,则该对象仍将进行验证。例如:{“foo”:“bar”}
将根据{“type”:“object”,“minProperties”:1,“properties”:{“test”:{“type”:“string”},“bar”:{“type”:“string”}}
@Benni验证“additionalProperties”:false怎么样?那就行了。阅读更多。