JSON schema to allow date or empty string

寵の児 提交于 2021-02-11 15:40:35

问题


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.


回答1:


Remove DateOfBirth from required list:

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

Supported JSON:

  1. DateOfBirth is set:
{    
    "FirstName": "Alex",
    "DateOfBirth": "1980-10-31"
}
  1. DateOfBirth isn't set:
{    
    "FirstName": "Alex",
}

Since you've added basic semantic validation for date values, you need to make sure the provided value follows the given format. Empty string ("") isn't a valid date format.



来源:https://stackoverflow.com/questions/61483435/json-schema-to-allow-date-or-empty-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!