当且仅当嵌套对象中存在特定键时,才需要JSON模式条件 [英] JSON Schema conditional required if and only if a specific key exists in nested object

查看:106
本文介绍了当且仅当嵌套对象中存在特定键时,才需要JSON模式条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对jsonschema的问题有两个方面:

My question for jsonschema is twofold:

给予

{
  "foo": {"ar": {"a": "r"}},
  "bar": ""
}

  1. 如何检查键"ar"是否在"foo"内部?

  1. How do I check if the key "ar" exists inside of "foo"?

并且仅当"ar"存在于"foo"内部时,如何才能使"bar"必须存在于给定的json中?

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

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

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

推荐答案

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

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

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

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

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.

这篇关于当且仅当嵌套对象中存在特定键时,才需要JSON模式条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆