gpt4 book ai didi

基于属性之一的 JSON 模式 anyOf 验证

转载 作者:行者123 更新时间:2023-12-04 06:16:33 25 4
gpt4 key购买 nike

我很难弄清楚如何根据其中一个属性的值来验证一组对象。所以我有一个 JSON 对象,如:

{
"items": [
{
"name": "foo",
"otherProperty": "bar"
},
{
"name": "foo2",
"otherProperty2": "baz",
"otherProperty3": "baz2"
},
{
"name": "imInvalid"
}
]
}

我想说
  • 项目可以包含 anyOf 对象,其中名称可以是“foo”或“foo2”
  • 如果它是“foo”,那么唯一有效的其他属性(必需)是
    “其他属性(property)”
  • 如果名称是“foo2”,则唯一有效的其他
    属性是“otherProperty2”和“otherProperty3”都需要
  • 除了“foo”和“foo2”之外,“name”的其他值都无效
  • 对象本身在 items 数组中是可选的,有些可能会重复。

  • 我尝试了各种方法,但在验证时似乎没有失败。例如,名称“imInvalid”应该会导致验证错误。这是我对架构的最新迭代。我错过了什么?
    {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "required": ["items"],
    "properties": {
    "items": {
    "type": "array",
    "minItems": 1,
    "additionalProperties": false,
    "properties": {
    "name": {
    "anyOf": [
    {
    "type": "object",
    "required": ["name", "otherProperty"],
    "additionalProperties": false,
    "properties": {
    "otherProperty": { "type": "string" },
    "name": { "enum": [ "foo" ] }
    }
    },{
    "type": "object",
    "required": ["name", "otherProperty2", "otherProperty3" ],
    "additionalProperties": false,
    "properties": {
    "otherProperty2": { "type": "string" },
    "otherProperty3": { "type": "string" },
    "name": { "enum": [ "foo2" ] }
    }
    }
    ]
    }
    }
    }
    }
    }

    最佳答案

    您已经掌握了使用 enum 来分隔匹配内容的基本思想,但这里有几个错误:

  • Json 模式数组没有 properties ,他们有 items .
  • 在这些属性中,您定义了 name作为一个属性,然后保存其他 json 模式对象。
  • 在您定义的架构的第二个分支中 otherProperty3但在您的示例中,该属性被称为 anotherProperty3

  • 试试这个稍微修改的版本:
    {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "required": ["items"],
    "properties": {
    "items": {
    "type": "array",
    "minItems": 1,
    "additionalProperties": false,
    "items": {
    "anyOf": [
    {
    "type": "object",
    "required": ["name", "otherProperty"],
    "additionalProperties": false,
    "properties": {
    "otherProperty": { "type": "string" },
    "name": { "enum": [ "foo" ] }
    }
    },{
    "type": "object",
    "required": ["name", "otherProperty2", "anotherProperty3" ],
    "additionalProperties": false,
    "properties": {
    "otherProperty2": { "type": "string" },
    "anotherProperty3": { "type": "string" },
    "name": { "enum": [ "foo2" ] }
    }
    }
    ]
    }
    }
    }
    }

    关于基于属性之一的 JSON 模式 anyOf 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36629866/

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