本文介绍了属性的互斥组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Jsonschema草稿6,我正在尝试创建符合以下条件的架构:

Using Jsonschema draft 6, I'm trying to create a schema that conforms to the following:

  1. 属性A,B1,B2和B3是数字或null
  2. 如果属性A存在且不为空,则属性B,C和D必须不存在或为空
  3. 如果属性B1,B2和B3中的任何一个存在且不为空,则属性A必须为空或不存在.
  4. A,B1,B2和B3可能都不存在
  1. Properties A, B1, B2, and B3 are either numbers or null
  2. If property A is present and non-null, then properties B, C, and D must be either absent or null
  3. If any of properties B1, B2, and B3 are present and non-null, then property A must be null or absent.
  4. A, B1, B2, and B3 may all be absent

符合证明文件的示例:

{}

{"A": 1}

{"A": 1, "B2": null}

{"B1": 1}

{"B1": 1, "B2": 1, "B3": 1}

{"A": null, "B1": 1, "B2": 1, "B3": 1}

不符合要求的文件示例:

Examples of non-conforming documents:

{"A": 1, "B1": 2}

{"A": 1, "B1": null, "B2": 1}

我看到了一些相关的问题可以帮助您,但并未完全回答问题:

I've seen some related questions that help but don't fully answer the question:

  • How to make anyOf a set of multually exclusive properties except one
  • Use json-schema to require or disallow properties based on another property value?
  • jsonSchema attribute conditionally required
  • How to define choice element in json schema when elements are optional?
  • How to define a JSON schema that requires at least one of many properties

这是我当前的架构,它仅强制执行约束#1和#4:

Here is my current schema, which only enforces constraint #1 and #4:

{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "properties": {
    "A": {"oneOf": [{"type": "null"}, {"type": "number"}],
    "B1": {"oneOf": [{"type": "null"}, {"type": "number"}],
    "B2": {"oneOf": [{"type": "null"}, {"type": "number"}],
    "B3": {"oneOf": [{"type": "null"}, {"type": "number"}]
  }
}

这里正确的方法是什么?我是在要求不合理的东西吗?

What is the right approach here? Am I asking for something unreasonable?

推荐答案

{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "oneOf": [
    {
      "properties": {
        "A": {"type": "number"},
        "B": {"type": "null"},
        "C": {"type": "null"},
        "D": {"type": "null"}
      },
      "required": ["A"]
    },
    {
      "properties": {
        "A": {"type": "null"},
        "B1": {"type": ["number","null"]},
        "B2": {"type": ["number","null"]},
        "B3": {"type": ["number","null"]}
      },
      "anyOf": [
        {"required": ["B1"]},
        {"required": ["B2"]},
        {"required": ["B3"]}
      ]
    },
    {
      "properties": {
        "A": {"type": "null"},
        "B1": {"type": "null"},
        "B2": {"type": "null"},
        "B3": {"type": "null"}
      }
    }
  ]
}

这篇关于属性的互斥组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 20:02