2

I can use jsonschema to specify that a value is a valid date in my JSON object, like so:

import jsonschema

schema = {'type': 'object', 'properties': {'dt': {'type': 'string', 'format': 'date'}}}

# fine
jsonschema.validate({'dt': '2017-01-01'}, schema, format_checker=jsonschema.FormatChecker())

# jsonschema.exceptions.ValidationError: 'not a date' is not a 'date'
jsonschema.validate({'dt': 'not a date'}, schema, format_checker=jsonschema.FormatChecker())

However, this leaves the value of dt unmodified, still as a string. I need to convert date/times to datetime.date/datetime.datetime instances, is there a way to do this automatically given a JSON schema (with jsonschema or any other library?

Ideally I would like something like this:

 import somelibrary

 schema = {'type': 'object', 'properties': {'dt': {'type': 'string', 'format': 'date'}}

 out = somelibrary.validate_and_parse({'dt': '2017-01-01'}, schema)
 assert out == {'dt': datetime.date(2017, 1, 1)}

 somelibrary.validate_and_parse({'dt': 'not a date'}, schema) # SomeError

I have a large project with many JSON documents which can be quite large and have many levels of nesting, so it's not as easy as simply looking up the keys myself and processing them after the object has been validated.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • I'm going to put this down as a likely duplicate. http://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date is a very good page that tells you how to parse a date-time from a string. In your case, just keep the validating and the parsing separate. After all, they are two separate tasks. – Scott Mermelstein Apr 03 '17 at 17:47
  • Possible duplicate of [How to parse an ISO 8601-formatted date?](http://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date) – Scott Mermelstein Apr 03 '17 at 17:47
  • What date would you like `'not a date'` converted into? – martineau Apr 03 '17 at 18:14
  • 1
    Just to be clear what I would like is to pass a JSON schema and a JSON blob to some function and have it validated *and* have date/times converted to `datetime.date`/`datetime.datetime` objects based on that schema – KX68C4qxM51mtdzex7O8iMPU Apr 04 '17 at 09:09

1 Answers1

1

you can make use of a serialization library such as Marshmallow to validate, serialize and deserialize your data.

Enrique Saez
  • 2,504
  • 16
  • 21