gpt4 book ai didi

json - 如何定义至少需要许多属性之一的 JSON 模式

转载 作者:IT老高 更新时间:2023-10-28 12:48:41 25 4
gpt4 key购买 nike

我想知道我是否可以定义一个 JSON 模式(草案 4),该模式至少需要一个对象的许多可能属性中的一个。我已经知道 allOfanyOfoneOf,但就是不知道如何以我想要的方式使用它们。

这里有一些示例 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"
}

我想至少要求 idemail (也接受它们)并且仍然根据格式通过验证。如果我同时提供两者(测试 3),则使用 oneOf 验证失败,即使其中一个无效(测试 4), 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"),那么它将传递 allOf .

关于json - 如何定义至少需要许多属性之一的 JSON 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31839578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com