Reputation: 153
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.
Upvotes: 2
Views: 1616
Reputation: 2700
you can make use of a serialization library such as Marshmallow to validate, serialize and deserialize your data.
Upvotes: 1