I want to output while converting the value of the type (e.g. datetime) that is not supported when outputting json with python.
You can use json.dumps (json.dump) when trying to convert dict to json in python. At this time, if a value of an unsupported type is included, the following exception will occur.
# TypeError: datetime.datetime(2000, 1, 1, 0, 0) is not JSON serializable
For example, if the dictionary person including datetime object is set to json.dumps specification, the result will be as follows.
import json
from datetime import datetime
person = {
"name": "Foo",
"age": 20,
"created_at": datetime(2000, 1, 1)
}
json.dumps(person)
# TypeError: datetime.datetime(2000, 1, 1, 0, 0) is not JSON serializable
json.dumps can take several arguments.
json.dumps = dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, inden
t=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)
Serialize ``obj`` to a JSON formatted ``str``.
...
If you give the following function to the default argument in this, you can specify the mapping for the unsupported one later.
def support_datetime_default(o):
if isinstance(o, datetime):
return o.isoformat()
raise TypeError(repr(o) + " is not JSON serializable")
Now you can convert it with json.dumps.
person = {
"name": "Foo",
"age": 20,
"created_at": datetime(2000, 1, 1)
}
json.dumps(person, default=support_datetime_default)
# {"created_at": "2000-01-01T00:00:00", "age": 20, "name": "Foo"}
You can change the class used for conversion to json.dumps with the cls argument (json.JSONEncoder is used by default) Therefore, it is OK to define a class that inherits JSONEncoder as shown below and pass it to cls.
class DateTimeSupportJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
return super(DateTimeSupportJSONEncoder, self).default(o)
json.dumps(person, cls=DateTimeSupportJSONEncoder)
# {"created_at": "2000-01-01T00:00:00", "age": 20, "name": "Foo"}
Recommended Posts