JSON 架构 : conditional dependency

标签 json jsonschema

我似乎不知道如何在 JSON 模式中实现某些目标。假设我有两个字段:statusquote

条件依赖如下:

  • 如果状态["Y", "N"],则引用必填<
  • 如果 status 是枚举中的任何其他内容,则quote 不需要
  • 如果 JSON 中不存在 status,则 quote 可以是任何内容

我正在尝试使用以下架构来实现此行为:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "quote": {
      "type": "string",
    },

    "status": {
      "type": "string",
      "enum": ["Y", "N", "M", "A", "S"]
    }
  },
  
  "oneOf": [
      {
        "properties": {
          "status": {"enum": ["Y", "N"]}
        },
        "required": [
          "quote"
        ]
      },
      {
        "properties": {
          "status": {"enum": ["Y", "N", "M", "A", "S"]}
        }
      }
  ]
}

前两个条件按预期工作,但每当 JSON 中省略 status 字段时,验证就会失败。想要的行为是,每当 status 字段不存在时,我都可以有一个字段 quote 为任何内容。

我怎样才能实现这个目标?

更新

所以我设法实现了我最初要求的目标,但是,我现在有额外的要求。也就是说,我有一个附加字段 author ,每当 status["M", "A"] 时都需要它,否则它只是可选的。如果 status 不存在,则 quoteauthor 都可以是任何内容。我尝试过如下:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "quote": { "type": "string" },
    "author": { "type": "string" },
    "status": { "enum": ["Y", "N", "M", "A", "S"] }
  },
  "allOf": [
    { "$ref": "#/definitions/y-or-n-requires-quote" },
    { "$ref": "#/definitions/m-or-a-requires-author" }
  ],
  "definitions": {
    "y-or-n-requires-quote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/status-is-y-or-n" } },
        { "required": ["quote"] }
      ]
    },
    "m-or-a-requires-author": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/status-is-m-or-a" } },
        { "required": ["author"] }
      ]
    },
    
    "status-is-y-or-n": {
      "properties": {
        "status": { "enum": ["Y", "N"] }
      }
    },
    
    "status-is-m-or-a": {
      "properties": {
        "status": { "enum": ["M", "A"] }
      }
    }
  }
}

但是,对于不存在 status 的 JSON,使用此架构不起作用。

最佳答案

请注意,draft-07 添加了“if”/“then”/“else”关键字以使条件更容易:

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-00#section-6.6

如果您的工具不支持 Draft-07,请考虑提交功能请求以更新它们:-)

关于JSON 架构 : conditional dependency,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47674950/

相关文章:

java - retorfit2 如何让这个 json 正确?

Python读取多行JSON

javascript - 将 JSON 数组与用户输入进行比较并获取值

ios - ios json解析成字典

javascript - Node.js 中的有效 JSON 发生位置 0 处 JSON 中的意外标记

json - 如何为包含 Properties 对象的对象定义 JSON 模式?

json - JSON Schema 中的 "required"与 "optional"有什么区别

java - 从单个 servlet 接收并解释不同类型的 JSON 对象

java - 无法从 POJO 生成 Json 架构

json - 如何在 JSON Schema (Ruby) 中生成所需的 "patternProperty"