2016-11-28 244 views
2

我無法在jsonschema無法使用日期驗證在jsonschema

myschema = { 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "type": "object", 
    "self": { 
     "primary_key": ["email"] 
    }, 
    "properties": { 
     "email": { 
      "pattern": "[^@][email protected][^@]+\.[^@]+" 
     }, 
     "dob": { 
      "description": "Date of Birth YYYY-MM-DD", 
      "type": "date" 
     } 
    } 
} 

使用「日期」類型驗證當我執行下面使用上述模式

from jsonschema import validate 
validate({ "dob": "2001-02-30"}, myschema) 

以下錯誤跟蹤代碼獲得

Unhandled Exception: 'date' is not valid under any of the given schemas 

Failed validating 'anyOf' in schema['properties']['properties']['additionalProperties']['properties']['type']: 
    {'anyOf': [{'$ref': '#/definitions/simpleTypes'}, 
       {'items': {'$ref': '#/definitions/simpleTypes'}, 
       'minItems': 1, 
       'type': 'array', 
       'uniqueItems': True}]} 

On instance['properties']['dob']['type']: 
    'date' 

更新:似乎日期的格式,而不是鍵入但它畢竟是讓我重點在n無效的日期。我可以在jsonschema代碼中清楚地看到它試圖使用datetime來解析它,但是我無法在那裏打斷點。

回答

1

date應作爲一個"format",而不是 「類型」:

"dob": { 
    "description": "Date of Birth YYYY-MM-DD", 
    "type": "string", 
    "format": "date" 
} 

然後,爲了檢查格式時,使用:

from jsonschema import validate, FormatChecker 

validate({"dob": "2001-02-30"}, myschema, format_checker=FormatChecker())