itasahobby
itasahobby

Reputation: 313

Is there a way to create an enum in jsonschema based on a same level property?

Description

I have a JSON Object with two properties (among others), that are category and subcategory,I have a function to get the list of categories and another one to get the subcategories for a given category.

So my schema looks something like this:

{
  "type": "array",
  "items": {
    "type": "obect",
    "properties": {
      "category": {
        "type": "string",
        "enum": getCategories()
      },
      "subcategory": {
        "type": "string",
        "enum": getSubcategories(category)
      }
  }
}

Note: One subcategory is in only one main category

Problem

The list of categories is large and I want to check with json schema that the category and subcategory are valid, so I wonder if there is a way of doing so.

Using npm package for node js

Example:

Let's assume i have the categories A and B with [A1,A2] and [B1,B2] , if the json to validate has the category A I want to check that the subcategory is in [A1,A2] not in [A1,A2,B1,B2]

What I've tried

Tried if-else statements from this other post but as I mentioned the list is large and doesn't look like a good practice at all

Upvotes: 0

Views: 982

Answers (1)

Ether
Ether

Reputation: 53996

At the moment, if/then constructs would be needed to specify the subcategory values based on category:

{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "category": {
        "type": "string",
        "enum": [ ... ]
      },
      "subcategory": {
        "type": "string",
      },
    },
    "allOf": [
      {
        "if": {
          "properties": {
            "category": { "const": "option1" },
          }
        },
        "then": {
          "properties": {
            "subcategory": {
              "enum": [ ... ]
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "category": { "const": "option2" },
          }
        },
        "then": {
          "properties": {
            "subcategory": {
              "enum": [ ... ]
            }
          }
        }
      },
      { ... }
    ] 
  }
}

However, there is a proposal to add a new keyword for the next draft specification which would shorten the syntax considerably: https://github.com/json-schema-org/json-schema-spec/issues/1082

Upvotes: 1

Related Questions