pboettch / json-schema-validator

JSON schema validator for JSON for Modern C++
Other
470 stars 135 forks source link

Nested object validation error #168

Open gabriel-turturica opened 2 years ago

gabriel-turturica commented 2 years ago

file schema.json

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "dataType": { "$ref": "#/$defs/datatypes-enum" }
  },
  "required": ["dataType"],
  "$defs": {
    "datatypes-enum": {
      "oneOf": [
        {
          "type": "string",
          "enum": ["bool", "boolA"]
        },
        {
          "type": "object",
          "patternProperties": {
            "^[a-zA-Z0-9_]+$": { "$ref": "#/$defs/datatypes-enum" }
          }
        }
      ]
    }
  }
}

file data.json

{
  "dataType": { "test": { "test": { "test": "bool" } } }
}

Expected results when validating data.json against schema.json: valid file (verified using https://www.jsonschemavalidator.net/ and jsonschema in python). Results I get: "schema with # /$defs/datatypes-enum/oneOf/0 already inserted".

Any advice would be appreciated.

pboettch commented 2 years ago

Interesting.

Your schema is using recursion. If your schema is valid then there is a bug in this project which prevents this schema to be parsed.

pboettch commented 2 years ago

OK, I found the problem: $defs is not the correct name for defintions in draft7, (it is definitions), so $defs is considered an unknown keyword - which is allowed to contain schemas for validation in draft7, if they are referenced somewhere within the schema - otherwise they are left unconsidered.

Because of that, this library parses unknown keywords-referenced-schemas on demand, which is different to known keywords (such as definitions) which are de-referenced, once everything is loaded.

What happens with the other validators if you name $defs to something unknown?

One solution/workaround here would be to consider $defs as a valid keyword, or you to change your schema to definitions.

Or parsing unknown keyword-schemas lazily as well - but this might be harder.

gabriel-turturica commented 2 years ago

Your debugging seems to be on point. I have changed from $defs to definitions and everything works fine. Thanks for the feedback.

pboettch commented 2 years ago

Glad you found a workaround, but the error you got is still a bug and needs to be fixed.