tobyink / p5-json-schema

1 stars 4 forks source link

Feature request - Strict mode #20

Open tobyink opened 3 years ago

tobyink commented 3 years ago

Migrated from rt.cpan.org #132625 (status was 'open')

Requestors:

From lnation@cpan.org on 2020-05-15 10:37:29 :

Would it be possible to pass an option "strict" that would then raise an error on unknown properties passed in the data. Take the following example that I would expect to fail with an error specifying that "thing" is an unknown property/key.

my $schema = '{ "$schema" : "http://json-schema.org/draft-07/schema#", "$id" : "https://example.com/arrays.schema.json", "title" : "The Root Schema", "description" : "A representation of a person, company, organization, or place", "type" : "object", "examples" : [ { "id" : 1, "checked" : false } ], "required" : [ "checked", "id" ], "properties" : { "checked" : { "$id" : "#/properties/checked", "title" : "The Checked Schema", "description" : "An explanation about the purpose of this instance.", "type" : "boolean", "examples" : [ true, false ] }, "id" : { "$id" : "#/properties/id", "title" : "The ID of the door", "description" : "This section represents the id of the door.", "type" : "integer", "examples" : [ 1 ] } } }';

my $data = '{ "checked": false, "id": 1, "thing": "not okay" }';

my $validator = JSON::Schema->new($schema, strict => 1); my $result = $validator->validate($data); # errors

tobyink commented 3 years ago

From edupuis@invoke.lu on 2020-08-31 15:10:24 :

Hi LNATION,

The JSON Schema specification actually allows for properties not listed in the properties array to be present in the data. [1]

To have the validation fail in this case, you need to use set the "additionalProperties" property for the object to false:

{ "$schema" : "http://json-schema.org/draft-07/schema#", "$id" : "https://example.com/arrays.schema.json", "type" : "object", "additionalProperties": false, "properties" : { "checked" : { "type" : "boolean", }, "id" : { "type" : "integer", } } }

Then you will get the following error:

$: The property thing is not defined in the schema and the schema does not allow additional properties

Also, note that specifying the required elements at the object level is not as you do, despite being conform to the JSON Schema specification, is not honoured by the JSON::Schema module, you have to add it to the property itself, as described in the ticket 95923.

I hope this helps,

Emmanuel Dupuis