Lombas
Lombas

Reputation: 1132

Is it possible to validate that default value type matches property type on the json schema?

var jsonSchema = @"{
            ""$schema"": ""https://json-schema.org/draft/2020-12/schema"",
            ""type"": ""object"",
            ""properties"": {
                ""isCommander"": {
                ""type"": ""boolean"",
                ""description"": ""Is a Commander on a star ship"",
                ""default"": ""thisIsStringNotBoolean""
                }
            }
        }";
var jsonSchemaObj = JsonSerializer.Deserialize<JsonSchema>(jsonSchema)!;

This code would throw some kind of error or I could call a method on jsonSchemaObj to find the inconsistency on the default value type.

Upvotes: 1

Views: 26

Answers (1)

gregsdennis
gregsdennis

Reputation: 8428

The short answer is "No, JSON Schema doesn't do that."

JSON Schema's default and examples keywords are annotations, meaning that their values are meta-data for consumers and don't participate in validation. There is an inherent difficulty in validating that these keywords adhere to the constraints of the schema that contains them.

Schema correctness is generally enforced by the meta-schema (a schema that validates schemas). When a schema is validated by its meta-schema, the schema is (usually) considered merely as the JSON data used to express it. There's no consideration that it is a schema.

For example, when validating

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "string"
}

against its meta-schema (identified by the $schema value), the above isn't really a schema, it's thought of as "just data", and the meta-schema is the "schema". Then you do a validation.

Because of this, when adding a default keyword:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "string",
  "default": false
}

there isn't any context that says the type keyword should be adding a constraint to the value of the default keyword. To the validation it's all just data, and the spec says that the value of default can be any JSON value.

(This is an oversimplification of meta-schema validation.)


The JSON Schema project feels that this kind of validation is best served by editors and language servers which can aid schema authorship by being specifically configured to detect these sorts of things. As such, a mere validator isn't really going to support this.

Upvotes: 2

Related Questions