I want to output while converting the value of the type (e.g. datetime) that is not supported when outputting json with python

I want to output while converting the value of the type (e.g. datetime) that is not supported when outputting json with python.

TypeError occurs in dictionaries containing unsupported types

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

By giving a function to the default argument, you can set a callback for the unsupported type.

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"}

Or create a class that inherits JSONEncoder

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

I want to output while converting the value of the type (e.g. datetime) that is not supported when outputting json with python
I want to output the beginning of the next month with Python
I want to initialize if the value is empty (python)
What to do when the value type is ambiguous in Python?
I want to display the number of num_boost_rounds when early_stopping is applied using XGBoost callback (not achieved)
I want to solve the problem of memory leak when outputting a large number of images with Matplotlib
I stumbled on the character code when converting CSV to JSON in Python
[Golang] I want to add omitempty to the json tag of the int type field of the structure so that it will be ignored if 0 is entered.
[Python Data Frame] When the value is empty, fill it with the value of another column.
Try to find the probability that it is a multiple of 3 and not a multiple of 5 when one is removed from a card with natural numbers 1 to 100 using Ruby and Python.
I want to inherit to the back with python dataclass
When writing to a csv file with python, a story that I made a mistake and did not meet the delivery date
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
I tried to find the entropy of the image with python
I want to specify another version of Python with pyvenv
I want to know the features of Python and pip
Keras I want to get the output of any layer !!
[Python3] List of sites that I referred to when I started Python
I want to extract an arbitrary URL from the character string of the html source with python
A story that didn't work when I tried to log in with the Python requests module
When incrementing the value of a key that does not exist
Convert to a string while outputting standard output with Python subprocess
The story that the version of python 3.7.7 was not adapted to Heroku
How to not escape Japanese when dealing with json in python
I want to use a wildcard that I want to shell with Python remove
I want to know the weather with LINE bot feat.Heroku + Python
Output the contents of ~ .xlsx in the folder to HTML with Python
When you want to print to standard output with print while testing with pytest
I want to run the Python GUI when starting Raspberry Pi
Timezone specification when converting a string to datetime type in python
I want to use both key and value of Python iterator
I want to check the position of my face with OpenCV!
I tried to improve the efficiency of daily work with Python
I want to debug with Python
I'm tired of Python, so I analyzed the data with nehan (corona related, is that word now?)
I tried to output the rpm list of SSH login destination to an Excel sheet with Python + openpyxl.
I want to get angry with my mom when my memory is tight
I tried to implement deep learning that is not deep with only NumPy
With PEP8 and PEP257, Python coding that is not embarrassing to show to people!
Python Note: When you want to know the attributes of an object
(Python Selenium) I want to check the settings of the download destination of WebDriver
I want to batch convert the result of "string" .split () in Python
I tried to get the authentication code of Qiita API with Python.
I want to express my feelings with the lyrics of Mr. Children
I want to identify the alert email. --Is that x a wildcard? ---
I want to stop the automatic deletion of the tmp area with RHEL7
I tried to get the movie information of TMDb API with Python
[Introduction to Python] What is the method of repeating with the continue statement?
I measured the speed of list comprehension, for and while with python2.7.
Python: I want to measure the processing time of a function neatly
I want to read CSV line by line while converting the field type (while displaying the progress bar) and process it.
I want to prevent the speaker connected to the Raspberry Pi (jessie) from bouncing when the OS is restarted (Python script)
How to deal with the problem that Japanese characters are garbled when outputting logs using JSON log formatter
[Python] How to deal with the is instance error "is instance () arg 2 must be a type or tuple of types"
[Python3] Code that can be used when you want to change the extension of an image at once
I'm an amateur on the 14th day of python, but I want to try machine learning with scikit-learn
I want to output to the console coolly
I want to analyze logs with Python
I want to play with aws with python
[python] [meta] Is the type of python a type?
I want to get the path of the directory where the running file is stored.