JSON Schema conditional required if and only if a specific key exists in nested object

Deadly 提交于 2020-01-17 01:00:12

问题


My question for jsonschema is twofold:

Given

{
  "foo": {"ar": {"a": "r"}},
  "bar": ""
}
  1. How do I check if the key "ar" exists inside of "foo"?

  2. And only if "ar" exists inside of "foo", how do I make it so that "bar" must exists inside the given json?

I have tried looking other SO answers or jsonschema docs, but they only seem to check if the key has a specific value rather than if the key just exists regardless of its value. And the jsonschema for nested objects only seem to check for the deepest level of the nest rather than somewhere in the middle.

I have come up with this, but it doesn't work.

{
  "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"
    ]
  }
}

回答1:


To test if the property is present, use the required keyword.

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

This schema validates to true if /foo/ar is present and false if it's not. Use this in place of your if schema and your conditional should work as expected.



来源:https://stackoverflow.com/questions/56299562/json-schema-conditional-required-if-and-only-if-a-specific-key-exists-in-nested

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!