Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validate json with recursive structure

I’m looking for a way to validate the following json using json-schema.

{
    "type": "node",
    "members": [
       "A",
       "B"
    ],
    "A": {
       "type": "node",
       "members": [
          "AA",
          "AB"
       ],
       "AA": {
        "type": "leaf"
       },
       "AB": {
        "type": "leaf",
        "1qola": "world"
       },
       "1itn9": 10
    },
    "B": {
        "type": "leaf"
    },
    "w81av": 5,
    "qm8yv": "hello"
}

The structure is a tree. Each member can be of type node or leaf and contains any number of child members and arbitrary attributes (e.g., w81av or 1qola in json).

How to validate the members field which is the list of child member names? So far, I’ve come up with the following json-schema.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "properties": {
        "type": {
            "type": "string",
            "enum": ["node", "leaf"]
        },
        "members": {
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    },
    "additionalProperties": {
        "anyOf": [
            {
                "$ref": "#"
            },
            {
                "type": ["boolean", "number", "string"]
            }
        ]
    },
    "required": ["type"]
  }

>Solution :

How to validate the members field which is the list of child member names?

I expect you mean that you want the members property in the data to be an array of the extra properties (additionalProperties) in the value, correct?

JSON Schema doesn’t support this kind of introspection, so unfortunately it’s not something that can be done with just JSON Schema.

The closest you can get is with my data vocabulary, using a JSON Path as the reference value. But even then, JSON Path doesn’t have a syntax to return a list of keys.

This is something that you will need to validate in code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading