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.

4
  • I'm going to put this down as a likely duplicate. stackoverflow.com/questions/127803/… 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. Commented Apr 3, 2017 at 17:47
  • Possible duplicate of How to parse an ISO 8601-formatted date? Commented Apr 3, 2017 at 17:47
  • What date would you like 'not a date' converted into? Commented Apr 3, 2017 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 Commented Apr 4, 2017 at 9:09

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.