0

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

itasahobby
  • 301
  • 4
  • 15
  • Are you saying you don't want to inline the list of categories in your schema? You can programmatically generate your schema to contain the list, but you can't embed code in the schema itself. JSON Schemas are data. – Ether Mar 30 '21 at 17:01
  • @Ether No, I don't mean that, sorry if the explanation wasn't on point. I mean that I would like each json be restricted to the subcategory list from the category that is explicit in the json if that makes sense at all, edited the question so it's more claryfying – itasahobby Mar 30 '21 at 17:10

1 Answers1

1

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

Ether
  • 53,118
  • 13
  • 86
  • 159