How do you model a recursive reference with JSON Schema without using arrays?

Viewed 359

My REST API returns JSON that look like the following Food object:

{
  "name": "Hare, meat only, stewed, weighed with bone",
  "category": {
    "name": "Hare",
    "parent": {
      "name": "Game",
      "parent": {
        "name": "Meat and meat products",
        "parent": null
      }
    }
  }
}

Each Food has a category, which can have a parent category, which can also have a parent category, i.e. food.category.parent.parent.

I have tried to model this with the following JSON Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$id": "https://www.example.com/schemas/food.json",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "category": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "parent": {
          "$ref": "#/$defs/parent_category"
        }
      }
    }
  },
  "$defs": {
    "parent_category": {
      "type": ["object", "null"],
      "properties": {
        "name": {
          "type": "string"
        },
        "parent": {
          "$ref": "#/$defs/parent_category"
        }
      }
    }
  }
}

But my server crashes with the following error:

Failed building the serialization schema for GET: /foods/:id, due to error Maximum call stack size exceeded

I was under the impression JSON Schema supported recursion, but I can see this might be limited to arrays. I am using Fastify, with schema-based validation.

Is it possible to construct a valid schema for my Food object without using arrays?

0 Answers
Related