14

Is it a valid json schema:

  object:
    $ref: '#/definitions/object'

Would you recommend to use such format?

Rana
  • 5,912
  • 12
  • 58
  • 91

1 Answers1

19

Self references are allowed and useful. However, your example looks like it would just be a referential infinite loop. Here is an example of a JSON Schema that uses recursive references to define a tree structure of unlimited depth.

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "tree": { "$ref": "#/definitions/tree" }
  },
  "definitions": {
    "tree": {
      "type": "object",
      "properties": {
        "value": { "type": "string" },
        "branches": {
          "type": "array",
          "items": { "$ref": "#/definitions/tree" },
          "minItems": 1
        }
      },
      "required": ["value"]
    }
  }
}
Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53
  • Is it possible to specify a maxDepth for the recursion? – Steve Amerige Mar 19 '18 at 15:43
  • 1
    Nope. There is no way in JSON Schema to know what depth you are at, so there is no way to limit at some depth. – Jason Desrosiers Mar 19 '18 at 17:44
  • Is it that this approach only works with "properties" but fails with "patternProperties"? I get `Unresolvable JSON pointer: 'definitions/tree'` if wrapped with `patternProperties" and uses a RegEx key like "^.*$". @JasonDesrosiers – kakyo Aug 22 '22 at 06:40
  • There's no reason why this wouldn't work with `patternProperties` or any other applicator. There's either some subtle error in your schema, or the validator you're using has a bug. – Jason Desrosiers Aug 22 '22 at 17:20