Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON schema to allow date or empty string

Tags:

json

I need to define a JSON schema wherein the input can either be a date or empty string.

My current JSON schema is

{
    "type": "object",    
    "required": [        
        "FirstName",        
        "DateOfBirth"
    ],
    "properties": {
        "FirstName": {
            "type": "string"
        },        
        "DateOfBirth": {            
            "type": "string", 
            "format": "date"
        }
    }
}

This allows

{    
    "FirstName": "Alex",
    "DateOfBirth": "1980-10-31"
}

but not

{    
    "FirstName": "Alex",
    "DateOfBirth": ""
}

How can I define the JSON schema so that DateOfBirth allows dates as well as empty string.

like image 313
A B Avatar asked Jun 21 '26 19:06

A B


1 Answers

Use anyOf to allow for an empty string:

{
  "type": "object",
  "required": [
    "FirstName",
    "DateOfBirth"
  ],
  "properties": {
    "FirstName": {
      "type": "string"
    },
    "DateOfBirth": {
      "anyOf": [
        {
          "type": "string",
          "format": "date"
        },
        {
          "type": "string",
          "maxLength": 0
        }
      ]
    }
  }
}
like image 159
Graham Parsons Avatar answered Jun 23 '26 12:06

Graham Parsons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!