Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON schema - valid if object does *not* contain a particular property

Is it possible to set up a JSON schema that still allows for additionalProperties but does not match if a very particular property name is present? In other words, I need to know if it's possible to have the exact opposite of the required declaration.

Schema:

{     "type": "object",     "properties": {         "x": { "type": "integer" }     },     "required": [ "x" ],     "ban": [ "z" ] // possible? } 

Match:

{ "x": 123 } 

Match:

{ "x": 123, "y": 456 } 

Do not match:

{ "x": 123, "y": 456, "z": 789 } 
like image 728
M Miller Avatar asked May 28 '15 19:05

M Miller


People also ask

How do I check if a JSON Schema is valid?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

What is JSON Schema properties?

Properties. The properties (key-value pairs) on an object are defined using the properties keyword. The value of properties is an object, where each key is the name of a property and each value is a schema used to validate that property.

What is JSON Schema validation?

JSON Schema validation asserts constraints on the structure of instance data. An instance location that satisfies all asserted constraints is then annotated with any keywords that contain non-assertion information, such as descriptive metadata and usage hints.

Is JSON Schema valid JSON?

JSON Schema is a JSON-based format for defining the structure of JSON data. It provides a contract for what JSON data is required for a given application and how to interact with it. It can be used for validation, documentation, hyperlink navigation, and interaction control of JSON data.


2 Answers

What you want to do can be achieved using the not keyword. If the not schema validates, the parent schema will not validate.

{     "type": "object",     "properties": {         "x": { "type": "integer" }     },     "required": [ "x" ],     "not": { "required": [ "z" ] } } 
like image 123
Jason Desrosiers Avatar answered Oct 22 '22 17:10

Jason Desrosiers


There is a simpler approach. Define that if x is present it must not satisfy any schema. By reduction to absurdity x can not be present:

{     "properties" : {         "x" : {             "not" : {}          }     } } 

Update 2020/04/16: As pointed out by @Carsten in a comment, from draft version 05 and above, the proposed schema can be simplified as follows:

{     "properties": {        "x": false     } } 
like image 24
jruizaranguren Avatar answered Oct 22 '22 16:10

jruizaranguren