1

我对 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"
    ]
  }
}
4

1 回答 1

2

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

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

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

于 2019-05-24T21:34:49.867 回答