Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there support in JSON Schema for deep object validation?

I was looking around the docs and couldn't find any direct or indirect solution.

Is there any way to get validation on JSON objects without knowing exactly where the specific object is located?

For example, I want to validate the following sub-object:

{
  "grandParent": {
    "parent": {
      "child": {
        "name": "John"
      }
    }
  }
}

The object can be part of a larger JSON file the can be structured as follows:

{
  "root": {
    "someKey": {
      "grandParent": ...
    },
    "grandParent": ...,
    ...<go in even deeper>: {
      "grandParent": ...
    }
  }
} 

Can I create a json schema that validates the object no matter where it is?

Similar example in glob would be: root.**.grandParent.parent.child

like image 922
Dima Brusilovsky Avatar asked Apr 29 '21 07:04

Dima Brusilovsky


1 Answers

You'll need to use a combination of additionalProperties, items, and recursive references.

First, we define the structure you want to validate. You have to define properties for each layer of the object.

Next, you want your root level to reference that definition. Because you're using pre draft 2019-09, you'll need to wrap that reference in an allOf.

Then you want to make sure that for objects, the values have the root schema applied, and for arrays, each item has the root schema applied.

The use of "$ref": "#" resolves to the root of the schema, which creates the cyclical reference.

Some implementations may not like this, but most should be able to handle it.

Here's a live demo of the below schema: https://jsonschema.dev/s/lBrZk

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "definitions": {
    "grandParentToChild": {
        "properties": {
          "grandParent": {
            "properties": {
              "parent": {
                "properties": {
                  "child": {
                    "properties": {
                      "name": {
                        "type": "string"
                      }
                    }
                  }
                }
              }
            }
          }
        }
    }
  },
  "allOf": [
    {
      "$ref": "#/definitions/grandParentToChild"
    }
  ],
  "additionalProperties": {
    "$ref": "#"
  },
  "items": {
    "$ref": "#"
  }
}
like image 157
Relequestual Avatar answered Dec 14 '22 18:12

Relequestual