代码之家  ›  专栏  ›  技术社区  ›  Philippe Schwyter

JSON模式:在additionalProperties中使用anyOf、oneOf和allOf

  •  5
  • Philippe Schwyter  · 技术社区  · 9 年前

    我试图验证一个对象,该对象可以具有任意键,其值可以是如下对象: { "href": "some string" }

    或包含与上述匹配的对象的数组。

    {
        "$schema": "http://json-schema.org/schema#",
        "id": "https://turnstyle.io/schema/links.json",
        "type": "object",
        "additionalProperties": {
            "oneOf": [
                {
                    "type": "object",
                    "required": "href"
                },
                {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "required": "href"
                    }
                }
            ]
        }
    }
    
    
    
    Passing example:
    {
        "customer": { "href": "/customer/1" },
        "products": [
            { "href": "/product/1" },
            { "href": "/product/2" }
        ]
    }
    
    Failing example:
    {
        "customer": { "wrongKey": "/customer/1" },
        "products": "aString"
    }
    

    可能吗?如果可能,正确的语法是什么?

    oneOf|anyOf|allOf 属于 additionalProperties 必须适用于以下所有键: 附加性质 .

    1 回复  |  直到 9 年前
        1
  •  4
  •   Pedro    8 年前

    “required”应该是一个属性数组,在 v4 .

    或“必需”:true(或false)作为v3中属性的一部分。

    试试这个:

    {
        "$schema": "http://json-schema.org/schema#",
        "id": "https://turnstyle.io/schema/links.json",
        "type": "object",
        "additionalProperties": {
            "oneOf": [
                {
                    "type": "object",
                    "properties": {
                      "href": {"type": "string"}
                    },
                    "required": ["href"]
                },
                {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                          "href": {"type": "string"}
                        },
                        "required": ["href"]
                    }
                }
            ]
        }
    }