JSON schema : “allof” with “additionalProperties”

前端 未结 4 1211
滥情空心
滥情空心 2020-12-13 12:08

Suppose we have schema following schema (from tutorial here):

{
  \"$schema\": \"http://json-schema.org/draft-04/schema#\",

  \"definitions\": {
    \"addr         


        
4条回答
  •  粉色の甜心
    2020-12-13 12:49

    Here's a slightly simplified version of Yves-M's Solution:

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "definitions": {
        "address": {
          "type": "object",
          "properties": {
            "street_address": {
              "type": "string"
            },
            "city": {
              "type": "string"
            },
            "state": {
              "type": "string"
            }
          },
          "required": [
            "street_address",
            "city",
            "state"
          ]
        }
      },
      "type": "object",
      "properties": {
        "billing_address": {
          "$ref": "#/definitions/address"
        },
        "shipping_address": {
          "allOf": [
            {
              "$ref": "#/definitions/address"
            }
          ],
          "properties": {
            "type": {
              "enum": [
                "residential",
                "business"
              ]
            },
            "street_address": {},
            "city": {},
            "state": {}
          },
          "required": [
            "type"
          ],
          "additionalProperties": false
        }
      }
    }
    

    This preserves the validation of required properties in the base address schema, and just adds the required type property in the shipping_address.

    It's unfortunate that additionalProperties only takes the immediate, sibling-level properties into account. Maybe there is a reason for this. But this is why we need to repeat the inherited properties.

    Here, we're repeating the inherited properties in simplified form, using empty object syntax. This means that properties with these names would be valid no matter what kind of value they contained. But we can rely on the allOf keyword to enforce the type constraints (and any other constraints) declared in the base address schema.

提交回复
热议问题