【问题标题】:Json schema - requiring fields based on field value from within the same nested objectJson 模式 - 需要基于同一嵌套对象中的字段值的字段
【发布时间】:2020-09-30 06:41:51
【问题描述】:

我有一个 JSON 请求,我正在尝试针对 JSON 模式进行验证。我想知道是否有可能要求子模式中的字段与同一子模式中的字段值不同?我试过 anyOf、OneOf 和 IF,然后,Else 无济于事。 anyOf 返回错误“2 个子模式中只有 1 个匹配”,OneOf 返回“2 个子模式匹配而不是一个”。

{
"field1":"aaa",
"field2":"bbb"
"field3":{ 
   "isTrue":true,
   "inner1":"1",
   "inner2":"1"
    }
}

那么对于上面的Json,如果字段isTrue为真,我可以只需要字段inner1和inner2吗?

"field3": {
                                "type": "object",
                                "properties": {
                                    "isTrue": {
                                        "type": 
                                            "boolean"
                                    },
                                    "inner1": {
                                        "type": 
                                            "integer"
                                    },
                                    "inner2": {
                                        "type": 
                                            "string"
                                    }
                                },
                                "anyOf": [
                                    {
                                        "properties": {
                                            "isTrue": {
                                                "const": "true"
                                            }
                                        },
                                        "required": [
                                            "inner1",
                                            "inner2"
                                        ]
                                    },
                                    {
                                        "properties": {
                                            "isTrue": {
                                                "const": "false"
                                            }
                                        },
                                        "required": [
                                            "isTrue"
                                        ]
                                    }
                                ]

                            }

以上是我冒犯的 Json 架构

【问题讨论】:

    标签: json jsonschema json-schema-validator


    【解决方案1】:

    如果您删除 "true""false" 周围的引号,您的架构应该可以工作——它们被视为字符串,而不是布尔值。

    (此外,您的数据对 inner1 和 inner2 都使用字符串,但架构希望其中的第一个是整数——这可能是一个转录错误。)

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 1970-01-01
      • 2015-04-09
      • 2020-05-08
      • 2019-12-17
      • 1970-01-01
      • 2017-12-09
      • 2015-01-21
      • 1970-01-01
      相关资源
      最近更新 更多