具有不同键集的子对象的JSON模式

问题描述 投票:1回答:1

我有JSON数据,它是一个数据数组,例如

[
  {
    "type": "background_color",
    "data": {
      "backgroundColor": "F9192D"
    }
  },
  {
    "type": "banner_images",
    "data": {
      "images": [
        {
          "url": "https://example.com/abc.jpg",
          "id": 3085
        },
        {
          "url": "https://example.com/zyx.jpg",
          "id": 3086
        }
      ]
    }
  },
  {
    "type": "description_box",
    "data": {
      "text": "Hello 56787"
    }
  }
]

数据是具有两个键typedata的对象数组。 data的类型和键将由其具有的数据的type定义。

[类似于background_color类型,data应该具有backgroundColor属性,而对于banner_imagesdata应该具有images,它是其他属性的数组。

到现在为止,我所做的是

{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "title": "category schema",
  "description": "Used to validate data of category",
  "examples": [],
  "required": [],
  "items": {
    "type": "object",
    "required": [
      "type",
      "data"
    ],
    "properties": {
      "type": {
        "type": "string",
        "enum": ["background_color", "banner_images", "description_box"]
      },
      "data": {
        "type": "object"        // How to define data property here for each use case
      }
    }
  }
}

我不知道如何为每个用例定义data属性?

json jsonschema json-schema-validator
1个回答
0
投票

您可以使用if/then/else块来定义条件约束。

ifthen的值是模式。如果if模式有效,则将应用then模式,否则allOf子模式(在此示例中为allOf[0])将通过验证。

有几种不同的方法可以做到这一点,但是当您没有任何其他或特殊要求时,这是干净的。如果愿意,请回来=]

在此示例中,我添加了banner_images ...

您可以通过here对其进行测试。

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "title": "category schema",
  "description": "Used to validate data of category",
  "items": {
    "type": "object",
    "required": [
      "type",
      "data"
    ],
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "background_color",
          "banner_images",
          "description_box"
        ]
      },
      "data": {
        "type": "object"
      }
    },
    "allOf": [
      {
        "if": {
          "properties": {
            "type": {
              "const": "banner_images"
            }
          }
        },
        "then": {
          "properties": {
            "data": {
              "required": [
                "images"
              ],
              "properties": {
                "images": {
                  "type": "array"
                }
              }
            }
          }
        }
      }
    ]
  }
}

作为参考,这是JSON Schema draft-7规范文档的一部分,详细说明了行为:https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6

© www.soinside.com 2019 - 2024. All rights reserved.