Search code examples
jsonjsonschemareusability

how can we link one jsonschema to another jsonschema


path of the file is E:\JSONSchema\Files\details.json

{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "id": {
        "type": "string"
      },
      "tagid": {
        "type": "string"
      }
    },
    "required": [
      "id",
      "tagid"
    ],
    "additionalProperties": false
  }
}

I want to reuse the above jsonschema in another file which is located in E:\JSONSchema\Core\visuals.json. How can I proceed to achieve it?


Solution

  • use $ref and provide an absolute path as a value

    Example:

    file path: E:\JSONSchema\Files\details.json

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "reuse": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "id": {
              "type": "string"
            },
            "tagid": {
              "type": "string"
            }
          },
          "required": [
            "id",
            "tagid"
          ],
          "additionalProperties": false
        }
      }
    }
    

    If I want to reuse in another file the sample code will look like

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "type": "object",
      "properties": {
        "firstName": {
          "type": "string"
        },
        "lastName": {
          "type": "string"
        },
        "IDs": {
          "$ref": "file:/E:/JSONSchema/Files/details.json#/reuse"
        }
      }
    }
    

    Another way of achieving this is by using id. Check the following code.

    {
          "$schema": "http://json-schema.org/draft-04/schema#",
          "id": "file:/E:/JSONSchema/Files/details.json",
          "type": "object",
          "properties": {
            "firstName": {
              "type": "string"
            },
            "lastName": {
              "type": "string"
            },
            "IDs": {
              "$ref": "#/reuse"
            }
          }
        }