I have a field status.
If the user is setting the job as draft status I don't want to require the description field - but I DO want to to have a default of empty string.
If the user is publishing the job than I want the description to be required.
What I cannot figure out is how in the "oneOf - draft" array to set a default for description.
Here is my schema
{
"schema": "http://json-schema.org/draft-04/schema#",
"$id": "http://company.com/schemas/job-update.json#",
"title": "Job",
"description": "Update job",
"type": "object",
"properties": {
"title": {
"type": "string",
"minLength": 2
},
"description": {
"type": "string"
// Can't set default here - as it will apply for the publish status.
},
"status": {
"enum": ["draft", "published", "onhold"],
"default": "draft"
}
},
"oneOf": [
{
"description": "Draft jobs do not require any validation",
"properties": {
"status": { "enum": ["draft"]}
},
"required": []
// SOME WHERE HERE SET DESCRIPTION.default: ""
},
{
"description": "Published jobs require validation on required fields",
"properties": {
"status": { "enum": ["published"]}
},
"required": [
"description"
],
}
],
"additionalProperties": false
}
Unfortunatly, this is not possible using pure JSON Schema.
JSON Schema validation does not modify the instance data.
The
default
key word in JSON Schema is an annotation key word. Annotation key words are used to denote information, however they have no validation requirements.Draft-7 (which is current) says this:
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-10.2
There is no defined behaviour associated with annotation key words.
Remember, the primary use case for JSON Schema is definition, validation, and annotation.
HOWEVER...
If you are not concerned about the portabliltiy of your schemas, the ajv implementation allows you to use the
default
value to set the key during validation, but this behaviour is not defined by JSON Schema.