How to specify defaults conditionally with JSON Schema

23.3k views Asked by At

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
}
1

There are 1 answers

3
Relequestual On

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:

There are no restrictions placed on the value of this keyword. When multiple occurrences of this keyword are applicable to a single sub-instance, implementations SHOULD remove duplicates.

This keyword can be used to supply a default JSON value associated with a particular schema. It is RECOMMENDED that a default value be valid against the associated schema.

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.