tristanpenman / valijson

Header-only C++ library for JSON Schema validation, with support for many popular parsers
BSD 2-Clause "Simplified" License
351 stars 105 forks source link

Enhancement: Support for simple recursive schemes #173

Open DrewMikola opened 1 year ago

DrewMikola commented 1 year ago

A common pattern (at least for me) is something like this:

(I'm using YAML here for ease of typing)

id: MySchema
properties:
  - name: 
       type: string
  - children:
       type: array
       items:
         $ref: "#" #Reference to this schema

This should validate a document where each object has a list of child objects that are of the same schema type as the parent object.

"Out of the box" valijson crashes with a stack-overflow, however I found a simple hack that enables this use case.

In schema_parser.h - makeOrReuseSchema:

        if (actualDocumentUri && (!currentScope || *actualDocumentUri != *currentScope)) {
            // Removed for brevity
        }
        // ADDED
        else if (*actualDocumentUri == *currentScope)
        {
            // Recursive document, return the parent schema
            return &rootSchema;
        }

This seems to work and handles the trivial example above.

A more robust solution would be capable of detecting any cyclic schema references. A simple solution would be an enhanced fetchDoc signature that would allow users to return a valijson::Schema document instead of an adapter document, pushing the problem to the user.

Thoughts?