我想知道我是否可以定义一个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": "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"
}
Run Code Online (Sandbox Code Playgroud)
我想要至少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"
}
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
你能帮助我如何为我的用例实现正确的验证吗?
clo*_*eet 64
要求至少一组属性,请required在一系列anyOf选项中使用:
{
"type": "object",
"anyOf": [
{"required": ["id"]},
{"required": ["email"]}
// any other properties, in a similar way
],
"properties": {
// Your actual property definitions here
}
{
Run Code Online (Sandbox Code Playgroud)
如果您想要的任何属性存在("id","email"),那么它将传递相应的选项allOf.
小智 7
您可以使用minProperties: number(maxProperties: number如果需要)。这将缩短模式定义:
{
type: "object",
minProperties: 1,
properties: [/* your actual properties definitions */],
}
Run Code Online (Sandbox Code Playgroud)
链接到文档:https : //json-schema.org/understanding-json-schema/reference/object.html#size
| 归档时间: |
|
| 查看次数: |
12239 次 |
| 最近记录: |