JSON schema to enforce array contents

前端 未结 2 782
没有蜡笔的小新
没有蜡笔的小新 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:20

    I have determined a solution that solves my problem, enforcing that A and B are present within the array, though does so positionally, thus requiring the JSON object I am validating to be ordered in some manner.

    Working Schema

    
    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "title": "Order dependent solution",
    
      "type": "array",
      "items": [
        {
          "$schema": "http://json-schema.org/draft-04/schema#",
          "title": "A Object",
    
          "type": "object",
          "required": ["id", "name"],
    
          "properties": {
            "id": {
              "type": "integer"
            },
            "name": {
              "type": "string",
              "enum": ["A"]
            }
          },
          "additionalProperties": false
        },
        {
          "$schema": "http://json-schema.org/draft-04/schema#",
          "title": "B Object",
    
          "type": "object",
          "required": ["id", "name"],
    
          "properties": {
            "id": {
              "type": "integer"
            },
            "name": {
              "type": "string",
              "enum": ["B"]
            }
          },
          "additionalProperties": false
        }
      ],
    
      "additionalItems": {
    
        "$schema": "http://json-schema.org/draft-04/schema#",
        "title": "C Object",
    
        "type": "object",
        "required": ["id", "name"],
    
        "properties": {
          "id": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          }
        },
        "additionalProperties": false  
      }
    
    }
    

    This JSON schema validates a JSON array containing a A object at index 0, a B object at index 1, and C objects composing all remaining elements. This solution is usable, and allows me to move forward with development, though a order independent solution would be prefered.

    Any help is appreciated! :)

    PS - These schemas are not optimized, and demonstrate redundancy, which I will remove in the final version by making use of the "id" and "$ref" keyword.

提交回复
热议问题