JSON schema to enforce array contents

前端 未结 2 772
没有蜡笔的小新
没有蜡笔的小新 2021-02-19 01:40

Hi all and thanks in advance.

I am attempting to create a JSON schema to enforce an array to contain one A and B object and N C objects, where A and B are C objects and

2条回答
  •  粉色の甜心
    2021-02-19 02:04

    What you are looking for is called "tuple typing".

    If the value of the items keyword is an array, then the items in the array data must match up with the schema in the corresponding position. Additional items (past the last index) are matched by additionalItems (or are disallowed if additionalItems is false).

    So, roughly what you want is something like:

    {
        "type": "array",
        "items": [
            {"$ref": "#/definitions/itemTypeA"},
            {"$ref": "#/definitions/itemTypeB"}
        ],
        "additionalItems": {"$ref": "#/definitions/itemTypeC"},
        "definitions": {
            ... actual definitions for A/B/C ...
        }
    }
    

    If you want to ensure that A and B exist, then you simply specify a minimum length using minItems, so there are at least two items (which because of "tuple typing", must match up with A and B).

    (This also assumes that A and B are the first items in the array. If that's not what you want, then it gets a bit more complicated - although there is a contains keyword proposed for v5 that would handle that neatly.)

    Slightly more detailed live demo:

    • Valid: [A, B]
    • Invalid: [A, C]
    • Valid: [A, B, C, C]

提交回复
热议问题