【问题标题】:JSON Schema conditional required if and only if a specific key exists in nested object当且仅当嵌套对象中存在特定键时才需要 JSON Schema 条件
【发布时间】:2019-10-11 11:09:34
【问题描述】:

我对 jsonschema 的问题是双重的:

给定

{
  "foo": {"ar": {"a": "r"}},
  "bar": ""
}
  1. 如何检查“foo”中是否存在键“ar”?

  2. 只有当“ar”存在于“foo”中时,我如何才能使“bar”必须存在于给定的json中?

我曾尝试查看其他 SO 答案或 jsonschema 文档,但他们似乎只检查键是否具有特定值,而不是键是否存在而不管其值如何。而且嵌套对象的 jsonschema 似乎只检查嵌套的最深层次,而不是中间的某个地方。

我想出了这个,但它不起作用。

{
  "definitions": {},
  "$schema": "https://json-schema.org/draft-07/schema#",
  "$id": "https://example.com/root.json",
  "type": "object",
  "properties": {
    "foo": {
      "type": "object"
    },
    "bar": {
      "type": "string"
    }
  },
  "required": [
    "foo"
  ],
  "if": {
    "properties": {
      "foo": {
        "properties": {
          "ar": {
            "type": "object"
          }
        }
      }
    }
  },
  "then": {
    "required": [
      "bar"
    ]
  }
}

【问题讨论】:

    标签: python python-3.x jsonschema python-jsonschema


    【解决方案1】:

    要测试属性是否存在,请使用required 关键字。

    {
      "properties": {
        "foo": {
          "required": ["ar"]
        }
      },
      "required": ["foo"]
    }
    

    如果/foo/ar 存在,则此架构验证为真,如果不存在,则验证为假。使用它代替您的 if 架构,您的条件应该按预期工作。

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多