JSON Schema Conditional Statements - json

I am trying to validate what I thought was a simple JSON schema as a configuration file for my Python application, it's a list of header key/value pairs, the only complication is that if the 'Type' field is set to 'AnyValue' then the value key is not required.
Here is the schema as it is:
{
"definitions":
{
'KeyEntry':
{
"properties":
{
'Type': {"type" : "string"},
'Key': {"type": "string"}
},
"required": ['Type', 'Key'],
"anyOf":
[
{
"if":
{
"properties": {'Type': {"const": 'ExactValue'}}
},
"then":
{
"properties":
{
'Value': {"type": "string"}
},
"required": ['Type', 'Key', 'Value'],
"additionalProperties": false
}
},
{
"if":
{
"properties": {'Type': {"const": 'AnyValue'}}
},
"then":
{
"required": ['Type', 'Key'],
"additionalProperties": false
}
}
]
}
},
"type": "object",
"properties":
{
'Keys':
{
"type": "array",
"items": {"$ref": "#/definitions/KeyEntry"}
}
},
"required": ['Keys']
}
Most of the validation works, except if I add extra values, even though I have set "additionalProperties": false throughout the schema.
Here is an example where extra values are accepted:
{
"Keys": [
{
"Type": "AnyValue",
"Key": "Version",
"Y": "Yes",
"N": "No",
}
]
}
Please can someone help explain where I have gone wrong and how I should correct it, please?

additionalProperties draft-07...
Validation with "additionalProperties" applies only to the child values of instance names that do not match any names in "properties", and do not match any regular expression in "patternProperties".
This means that additionalProperties is only aware of keywords which appear in properties or that match the regex from patternProperties. Using additionalProperties with required without properties is going to create a dud schema (nothing will pass validation).
In stead, you can separate the concerns into what you actually want...
You want type, key, and value, to all be strings.
One of...
If type is AnyValue, then require type and key only.
If type is ExactValue, then require type, key, and value.
This is also easier to understand. Here's a live demo with your data.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"KeyEntry": {
"properties": {
"Type": {
"type": "string"
},
"Key": {
"type": "string"
},
"Value": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"Type",
"Key"
],
"anyOf": [
{
"if": {
"properties": {
"Type": {
"const": "ExactValue"
}
}
},
"then": {
"required": [
"Type",
"Key",
"Value"
]
},
"else": false
},
{
"if": {
"properties": {
"Type": {
"const": "AnyValue"
}
}
},
"then": {
"required": [
"Type",
"Key"
]
},
"else": false
}
]
}
},
"type": "object",
"properties": {
"Keys": {
"type": "array",
"items": {
"$ref": "#/definitions/KeyEntry"
}
}
},
"required": [
"Keys"
]
}

Related

If-then condition in JSON Schema isn't working

Following is the jsonSchema.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": [
{
"type": "object",
"properties": {
"isMerchant": {
"type": "boolean"
},
"isAgent": {
"type": "boolean"
},
"cashLoan": {
"type": "boolean"
},
"personalDetail": {
"type": "string"
},
"contact": {
"type": "object",
"properties": {
"email": {
"type": "string"
},
"mobile": {
"type": "integer"
},
"area": {
"type": "string"
},
"state": {
"type": "string"
}
},
"required": ["state"]}
},
"required": ["isMerchant","cashLoan","contact"],
"allOf": [
{
"if": {
"properties": {
"isMerchant": {"enum": [true]}
}
},
"then": {
"required": [ "isAgent","email","mobile"]
}
},
{
"if": {
"properties": {
"cashLoan": {"enum": [true]}
}
},
"then": {
"required": ["personalDetail"]
}
}
]
}
]
}
Expectation is to validate the corresponding JSON data with this JSON schema. where conditions are as follows -
If 'isMerchant' = true then the params 'isAgent', 'email', 'mobile' should be present in the json file.
If 'cashLoan' = true then param 'personalDetail' should be present.
With draft 2020-12, the type of the items keyword can only be object or boolean.
You need to add a "requires": [...] to your if conditions, because the properties keyword will evaluate to true if the property is not present at all, therefore you are entering the then conditionals when you don't intend to.

JSON-Schema add property to the item conditionally

I have the following JSON data
[
{
"type": "social_media_profiles",
"data": {
"profiles": [
{
"key": "twitter",
"data": "username",
"field": "handle",
"label": "Tweet"
},
{
"key": "customLink",
"data": "abc",
"field": "url",
"label": "Click",
"color": {
"button": "red",
"text": "green",
"border": "yellow"
}
}
]
}
}
]
and following jsong schema
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"additionalProperties": false,
"items": {
"type": "object",
"required": ["type", "data"],
"additionalProperties": false,
"properties": {
"type": {
"type": "string",
"enum": [
"social_media_profiles"
]
},
"data": {
"type": "object"
}
},
"allOf": [
{
"if": {
"properties": {
"type": {
"const": "social_media_profiles"
}
}
},
"then": {
"properties": {
"data": {
"type": "object",
"required": ["profiles"],
"additionalProperties": false,
"properties": {
"profiles": {
"type": "array",
"items": {
"type": "object",
"required": ["data", "field", "key"],
"additionalProperties": false,
"properties": {
"data": {
"type": "string",
"description": "Data contains either profile url, handle id, etc."
},
"field": {
"type": "string",
"enum": ["url", "handle", "id", "tel"],
"description": "Type of field value."
},
"key": {
"type": "string",
"description": "Social media name used to distinguish each social network"
},
"label": {
"type": "string",
"description": "Label to display on the landing page"
}
},
"allOf": [
{
"if": {
"properties": {
"key": {
"const": "customLink"
}
}
},
"then": {
"properties": {
"color": {
"type": "object",
"additionalProperties": false,
"required": [],
"properties": {
"button": {
"type": "string"
},
"text": {
"type": "string"
},
"border": {
"type": "string"
}
}
}
}
}
}
]
}
}
}
}
}
}
}
]
}
}
I want to add new property color to the profiles item based on the condition when key of the item is customLink.
If key is not customLink then color property should not be there.
Validating the schema from https://www.jsonschemavalidator.net/ is giving error
Found 2 error(s)
Message: JSON does not match all schemas from 'allOf'. Invalid schema indexes: 0.
Schema path: #/items/allOf
Message: JSON does not match schema from 'then'.
Schema path: #/items/allOf/0/then/then
How can I append new property conditionally based on the sibling property value?
In your profiles.items schema, you defined additionalProperties: false.
additionalProperties depends on the properties defined in the same schema object, meaning that color would always be dissallowed.
You can separate out your concerns into "what properties are allowed", and "if their values are valid".
Moving the validation for the color object into profiles.properties allows you to maintain additionalProperties: false in that object level.
The schema values of the properties object are only applied to the instance location for the keys, if they exist (hence needing to use required to require that specific keys are... required).
Having simplified the condional section, you end up with a cleaner Schema.
You now only need to define the condition under which color is required, without worrying about what the value should look like.
Sudo code: if key is customLink, then require color, else dissallow color.
{
"if": {
"properties": {
"key": {
"const": "customLink"
}
}
},
"then": {
"required": [
"color"
]
},
"else": {
"not": {
"required": [
"color"
]
}
}
}
Using not, you can invert the validation result of the applied subschema, which is what you need to do when you want to define that a specific property is NOT allowed.
Here's a live demo to play with: https://jsonschema.dev/s/C9V6N
And for prosperity, here's the full schema, with one or two redundancies removed.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": {
"type": "object",
"required": [
"type",
"data"
],
"additionalProperties": false,
"properties": {
"type": {
"type": "string",
"enum": [
"social_media_profiles"
]
},
"data": {
"type": "object"
}
},
"allOf": [
{
"properties": {
"data": {
"type": "object",
"required": [
"profiles"
],
"additionalProperties": false,
"properties": {
"profiles": {
"type": "array",
"items": {
"type": "object",
"required": [
"data",
"field",
"key"
],
"additionalProperties": false,
"properties": {
"data": {
"type": "string",
"description": "Data contains either profile url, handle id, etc."
},
"field": {
"type": "string",
"enum": [
"url",
"handle",
"id",
"tel"
],
"description": "Type of field value."
},
"key": {
"type": "string",
"description": "Social media name used to distinguish each social network"
},
"label": {
"type": "string",
"description": "Label to display on the landing page"
},
"color": {
"type": "object",
"additionalProperties": false,
"properties": {
"button": {
"type": "string"
},
"text": {
"type": "string"
},
"border": {
"type": "string"
}
}
}
},
"allOf": [
{
"if": {
"properties": {
"key": {
"const": "customLink"
}
}
},
"then": {
"required": [
"color"
]
},
"else": {
"not": {
"required": [
"color"
]
}
}
}
]
}
}
}
}
}
}
]
}
}

JSON Schema oneOf validation

I'm trying to create a JSON Schema that will allow a property to be either a number or an object of a specific format.
My data looks like this:
{
"num": 200
}
and my Schema looks like this:
{
"properties": {
"num": {
"type": [
"number",
"object"
],
"oneOf": [
{
"type": "number"
},
{
"$ref": "#/definitions/Variable"
}
]
}
},
"required": [
"num"
],
"additionalProperties": false,
"definitions": {
"Variable": {
"title": "Variable",
"properties": {
"$variable$": {
"type": "boolean",
"example": true
},
"name": {
"type": "string"
},
"defaultValue": {
"type": [
"string",
"object",
"number"
]
}
},
"required": [
"$variable$",
"name"
],
"additionalProperties": false
}
}
}
When I run it via a validator here: https://www.jsonschemavalidator.net/
I get this error:
Message: JSON is valid against more than one schema from 'oneOf'. Valid schema indexes: 0, 1.
Schema path: #/properties/num/oneOf
I'm assuming I'm missing something obvious about how oneOf works, but I can't figure out what it might me. Would appreciate any help here, thanks!
The error you are getting is telling you that both of you oneOf schemas are validating as true. It might be surprising that the value 4 is valid against the following schema.
{
"properties": {
"foo": { "type": "string": }
},
"required": ["foo"]
}
It turns out that the properties keyword and the required keyword don't apply when the value is not an object. So, the above schema is effectively the empty schema ({}) when validating against a number (or anything that is not an object). Because the empty schema means there are no constraints, everything is valid.
To fix your problem just add "type": "object" to your /definitions/Variable schema.
For your case you don't need oneOf at all, you can simply use
"type": ["number",{"$ref":"#/definitions/Variable"}] instead of "type": ["number","object"]
{
"properties": {
"num": {
"type": [
"number",{"$ref":"#/definitions/Variable"}
]
}
},
"required": [
"num"
],
"additionalProperties": false,
"definitions": {
"Variable": {
"title": "Variable",
"properties": {
"$variable$": {
"type": "boolean",
"example": true
},
"name": {
"type": "string"
},
"defaultValue": {
"type": [
"string",
"object",
"number"
]
}
},
"required": [
"$variable$",
"name"
],
"additionalProperties": false
}
}
}

why doesn't json schema validate definitions defined in required attribute

I'm trying to create a json schema that validates an object depending on its type. It picks the right definition, however, it doesn't validate the required attributes in the selected definition. Here is the json schema i am trying:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"literal": {
"type": "object",
"properties": {
"raw": { "type": "string" }
},
"required": ["raw"],
"additionalProperties": false
},
"identifier": {
"type": "object",
"properties": {
"name": { "type": "string" }
},
"required": ["name"],
"additionalProperties": false
}
},
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"type": {
"enum": ["Literal"]
},
"content": { "$ref": "#/definitions/literal" }
}
},
{
"type": "object",
"properties": {
"type": {
"enum": ["Identifier"]
},
"content": { "$ref": "#/definitions/identifier" }
}
}
],
"required": ["type"]
};
the following schema is valid, even tho its missing the "raw" property:
{ "type" : "Literal" }
thanks
There is no keyword content in JSON Schema spec.
Once you have asserted "type":"object" in root schema, there is no need to do it again in subschema.
In order to combine object type enumerated value with associated extended definition, you need allOf keyword.
Also in definitions if you use "additionalProperties": false you have to list all properties of the object (see "type": {}). For previously defined/validated properties you can just use permissive schema: {} or true.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"literal": {
"properties": {
"type": {},
"raw": { "type": "string" }
},
"required": ["raw"],
"additionalProperties": false
},
"identifier": {
"properties": {
"type": {},
"name": { "type": "string" }
},
"required": ["name"],
"additionalProperties": false
}
},
"type": "object",
"oneOf": [
{
"allOf": [
{
"properties": {
"type": {
"enum": ["Literal"]
}
}
},
{"$ref": "#/definitions/literal"}
]
},
{
"allOf": [
{
"properties": {
"type": {
"enum": ["Identifier"]
}
}
},
{"$ref": "#/definitions/identifier" }
]
}
],
"required": ["type"]
}

JSON schema validdation - oneOf with array of mixed object type

I am trying to build up a JSON schema, where the JSON data has an array of mixed object types. I am trying to use oneOf, however, it seems that I am missing something, as my JSON data fails to validate against the schema.
Below are what I have done so far.
Schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"definitions": {
"Entity": {
"type": "object",
"additionalProperties": false,
"properties": {
"Property": {
"type": "string"
},
"Value": {
"type": "string"
}
},
"required": [ "Property", "Value" ]
},
"NavEntity": {
"type": "object",
"additionalProperties": false,
"properties": {
"Property": {
"type": "string"
},
"NavigationalEntities": {
"type": "array",
"items": {
"$ref": "#/definitions/Entity"
}
}
},
"required": [ "Property", "NavigationalEntities" ]
}
},
"additionalProperties": true,
"name": "/",
"properties": {
"Entities": {
"type": "array",
"minLength": 1,
"uniqueItems": true,
"items": {
"oneOf": [
{ "$ref": "#/definitions/Entity" },
{ "$ref": "#/definitions/NavEntity" }
],
"additionalProperties": false
}
}
}
}
And here is my JSON data:
{
"Entities": [
{
"Property": "ABC",
"NavigationalEntities": [
{
"Property": "ABC1",
"Value": "123"
}
]
},
{
"Property": "ABCD",
"Value": "ABCD"
}
]
}
When I try to validate this, I get error: "Additional properties not allowed". This can also be seen here.
Please let me know what I am missing here.
The problem is the "additionalProperties": false included in the items keyword within the Entities property.
You are specifying both:
all items should not have any additional properties that those
defined in items object (and you did not define any).
all items must verify one of Entity or NavEntity.
If you remove the last "additionalProperties": false, everything is ok. And you don't need it because both Entity and NavEntity have it included.
Proposed schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"definitions": {
"Entity": {
"type": "object",
"additionalProperties": false,
"properties": {
"Property": {
"type": "string"
},
"Value": {
"type": "string"
}
},
"required": [ "Property", "Value" ]
},
"NavEntity": {
"type": "object",
"additionalProperties": false,
"properties": {
"Property": {
"type": "string"
},
"NavigationalEntities": {
"type": "array",
"items": {
"$ref": "#/definitions/Entity"
}
}
},
"required": [ "Property", "NavigationalEntities" ]
}
},
"additionalProperties": true,
"name": "/",
"properties": {
"Entities": {
"type": "array",
"minLength": 1,
"uniqueItems": true,
"items": {
"oneOf": [
{ "$ref": "#/definitions/Entity" },
{ "$ref": "#/definitions/NavEntity" }
]
}
}
}
}