What to do if there is a decimal in python json .dumps


For example, if you handle int / float numerical data in DynamoDB, the data will be retrieved as decimal. When I run python's standard json.dumps on queries and get items that contain such data, I get an exception due to the unconvertible type. So, I always forget how to deal with this, so I will leave a note. (Similar and similar happens with Datetime type) If json.dumps fails with a type error, you can deal with it by preparing a conversion function.

In the first place

You can specify default as an argument to json.dumps. By setting the conversion function here, you can handle the non-target type by yourself and convert it to your favorite type. Excerpt from the official below

If you specify> default, specify a function, and this function will be called for objects that cannot be serialized otherwise. The function must either return the object in a JSON-encoded version or raise a TypeError. If not specified, TypeError will be thrown.


Prepare a conversion function.

from decimal import Decimal

def decimal_to_int(obj):
    if isinstance(obj, Decimal):
        return int(obj)

When running json.dump

json.dumps(your_val, default=decimal_to_int)

Just set the conversion function in the default argument.

This time, I only wrote to convert decimal, but if you prepare the type check and conversion logic expected for the type conversion function, it is possible to support multiple types. For example, datetime is returned as a string formatted with strftime. So, it would be useful if you could understand the structure of the functions that you use for granted. So, if you want to understand it properly, please check here.

It's a very short article, but I always forget it, so it's almost my own memo.

What else?

simplejson seems to support many types. I have never used it. If you want to use it with AWS Lambda, it is not included in the standard package, so [Add it to the package yourself](https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/python-package. You need to register as [html) or Lambda layer.

Recommended Posts

What to do if there is a decimal in python json .dumps
What to do if you get a minus zero in Python
What to do if a UnicodeDecodeError occurs in pip
What to do if a Unicode Encode Error occurs in Sublime Text Python
What to do if  Ľarguments [0] .scrollIntoView ();` fails in python selenium
What to do if pip gives a DistributionError in Homebrew
What to do if a 0xC0000005 error occurs in tf.train.start_queue_runners ()
What to do if the progress bar is not displayed in tqdm of python
What to do if Python IntelliSense is not displayed in VS Code on Windows
What to do if "Unnamed: 0" is added in to_csv-> read_csv in pandas
What to do when the value type is ambiguous in Python?
What to do when there is no response due to Proxy setting in Python web scraping
What to do if pipreqs results in UnicodeDecodeError
What to do if you can't use scikit grid search in Python
How to create a JSON file in Python
What to do if No Python documentation found for ... appears in pydoc
What to do to get google spreadsheet in python
What happens if you do "import A, B as C" in Python?
What is the fastest way to create a reverse dictionary in python?
What to do when a warning message is displayed in pip list
What to do if an error message "There was a problem displaying this web page" is displayed in Chrome's Web Driver (Selenium)
What to do if PyInstaller3.5 gives an error in Python3.8 (TypeError: an integer is required (got type bytes))
[Python] What to do if you get a ModuleNotFoundError when importing pandas using Jupyter Notebook in Anaconda
What to do if a symbolic link error occurs in import cv while trying to install OpenCV in Python
[Python] What to do if an error occurs in pip (pyinstaller, pyautogui, etc.)
What to do if you get a "No versions found" error in pipenv
What to do when a warning appears around Python integration in Neovim's CheckHealth
What to do if you get "Python not configured." Using PyDev in Eclipse
What to do if abort is displayed when inputting camera video in OpenCV
What to do if NotADirectoryError: [Errno 20] Not a directory:'xdg-settings' appears in jupyter notebook
What to do if a version error occurs in the selenium Chrome driver
Check if the string is a number in python
Parse a JSON string written to a file in Python
What to do if pip install fails in Xcode 5.1
What to do if pyenv is not enabled (zsh)
What is a python map?
I created a script to check if English is entered in the specified position of the JSON file in Python.
What to do if you get `No kernel for language python found` in Hydrogen
What to do if the print command itself causes an error in Maya python
What to do if you get an error when importing matplotlib in Python (Mac)
How to check in Python if one of the elements of a list is in another list
What to do if Sort imports get stuck in VS Code's Python Extension (around 2020/09)
What to do if Python does not switch from the System version in pyenv
What to do if you can't hit the arrow keys in the Python interactive console
What to do if you run python in IntelliJ and end with an error
What to do if you get the error RuntimeError: Python is not installed as a framework when trying to use matplitlib and pylab in Python 3.3
Why do you add a main ()-if statement in Python?
What to do if you get "coverage unknown" in Coveralls
What to do when "SSL: CERTIFICATE_VERIFY_FAILED _ssl.c: 1056" appears in Python
What to do if you can't log in as root
[Python] What is a zip function?
[Python] What is a with statement?
[Python] How to do PCA in Python
What to do if yum breaks
Is there a special in scipy? ??
What to do if the image is not displayed using matplotlib etc. in the Docker container
What to do when a Missing artifact occurs in a jar that is not defined in pom.xml
What to do with PYTHON release?
What to do if you get Swagger-codegen in python and Import Error: No module named
There is no switch in python
What to do if you get a Cannot retrieve metalink for repository error in yum