本文介绍了JSON模式对值的条件依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这里有一个类似的问题,但是并没有真正解决我的问题.简而言之,我希望我的一个字段依赖于另一个字段的值.但是对于某些值,我不要求任何字段.这是一个示例:

I know there is a similar question here, but it didn't really address my issue. In short, I want one my fields to be dependent on the other field's value. But for some values, I don't want any field to be required. Here is an example:

架构

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

    "colour": {
      "type": "string",
      "enum": ["red", "black", "blue"]
    },

    "blackQuote": {
      "type": "string",
      "maxLength": 11
    },

    "redQuote": {
      "type": "string",
      "maxLength": 11
    }
  },

  "oneOf": [
      {
        "properties": {
          "colour": {"enum": ["red"]}
        },
        "required": ["redQuote"]
      },
      {
        "properties": {
          "colour": {"enum": ["black"]}
        },
        "required": ["blackQuote"]
      }
  ],

  "required": [
    "colour"
  ]
}

这是这样的:

  • 如果颜色是红色",则需要"redQuote"(而不是"blackQuote"):这很好
  • 如果颜色是黑色",则需要"blackQuote"(而不是"redQuote"):这也很好
  • 但是,如果我将颜色"blue"放入JSON中,则验证程序会说缺少"redQuote"和"blackQuote"属性...我不希望那样,我只想依赖于"red"和黑色",但是如果颜色是蓝色",则不需要任何内容​​.如何实现这一目标?

推荐答案

您可以使用称为蕴含(!A或B)的布尔逻辑概念来做到这一点.它可以像"if-then"语句一样使用.例如,"color"不是"red"或"redQuote"是必需的.每当我需要使用它时,我都会用definitions对其进行分解,以使其读得尽可能好.

You can do this with a boolean logic concept called implication (!A or B). It can be used like an "if-then" statement. For example, either "color" is not "red" or "redQuote" is required. Any time I need to use this, I break it down with definitions so it reads as nice as possible.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "colour": { "enum": ["red", "black", "blue"] },
    "blackQuote": { "type": "string", "maxLength": 11 },
    "redQuote": { "type": "string", "maxLength": 11 }
  },
  "allOf": [
    { "$ref": "#/definitions/red-requires-redQuote" },
    { "$ref": "#/definitions/black-requires-blackQuote" }
  ],
  "required": ["colour"],
  "definitions": {
    "red-requires-redQuote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/is-red" } },
        { "required": ["redQuote"] }
      ]
    },
    "black-requires-blackQuote": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/is-black" } },
        { "required": ["blackQuote"] }
      ]
    },
    "is-red": {
      "properties": {
        "colour": { "enum": ["red"] }
      }
    },
    "is-black": {
      "properties": {
        "colour": { "enum": ["black"] }
      }
    }
  }
}

这篇关于JSON模式对值的条件依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:58