This post was originally published here
We just released a new version of our Azure Function JSON Schema Validation, adding support for more complex schema validations. In this case, we add support for applying subschemas validation conditionally.
The if
, then
and else
keywords allow the application of a subschema based on the outcome of another schema, much like the if
/then
/else
constructs you’ve probably seen in traditional programming languages.
- If
if
is valid,then
must also be valid (andelse
is ignored.) Ifif
is invalid,else
must also be valid (andthen
is ignored). - If
then
orelse
is not defined,if
behaves as if they have a value oftrue
. - If
then
and/orelse
appear in a schema withoutif
,then
andelse
are ignored.
JSON Schema Validation Function
The JSON Schema Validation is a simple Azure Function that allows you to validate your JSON message against a JSON Schema, enabling you to specify constraints on the structure of instance data to ensure it meets the requirements.
The function receives a JSON payload with two properties:
- The JSON message in the json property.
- And the JSON Schema in the jsonSchema property.
Example:
{
"json": {
"address": [
{
"contact": {
"firstName": "myFirstName",
"lastName": "myLastName"
},
"type": "bill"
}
]
},
"jsonSchema": {
"type": "object",
"properties": {
"address": {
"type": "array",
"items": {
"type": "object",
"properties": {
"contact": {
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
}
},
"required": []
},
"type": {
"type": "string"
}
},
"required": [
"contact",
"type"
]
}
}
},
"if": {
"properties": {
"address": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {
"const": "bill"
}
}
}
}
}
},
"then": {
"properties": {
"address": {
"type": "array",
"items": {
"type": "object",
"properties": {
"contact": {
"required": [
"firstName"
],
"properties": {
"firstName": {
"type": "string"
}
}
}
}
}
}
}
},
"else": {
"properties": {
"address": {
"type": "array",
"items": {
"type": "object",
"properties": {
"contact": {
"required": [],
"properties": {}
}
}
}
}
}
}
}
}
The function’s output will be:
- A 200 OK if the JSON message is valid.
- Or a 400 Bad Request if there are validation errors/issues.
Where can I download it?
You can download the complete Azure Functions source code here:
Download JSON Schema Validation Azure Function
Hope you find this helpful! So, if you liked the content or found it helpful and want to help me write more content, you can buy (or help buy) my son a Star Wars Lego!
Big thanks to my team member Luís Rigueira for adding this new feature.