TypeError: Object of type function is not JSON serializable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: Object of type function is not JSON serializable #

The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.

Here is an example of how the error occurs.

main.py
import json def get_employee(): return {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type function is not JSON serializable json_str = json.dumps(get_employee) # 👈️ forgot to call function

We forgot to call the get_employee() function in the call to the json.dumps() method.

To solve the error, make sure to call the function and serialize its return value rather than the function itself.

main.py
import json def get_employee(): return {'name': 'Alice', 'age': 30} # ✅ call function get_employee() and NOT get_employee json_str = json.dumps(get_employee()) print(json_str) # 👉️ '{"name": "Alice", "age": 30}' print(type(json_str)) # 👉️ <class 'str'>

The json.dumps method converts a Python object to a JSON formatted string.

We called the function, so we serialized the dict object rather than trying to serialize the function itself.

You have to add parentheses to call a function, e.g. get_employee(), otherwise we pass a reference to the get_employee function to the json.dumps method which is not what we want.

The JSONEncoder class supports the following objects and types by default.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

The JSONEncoder class doesn't support function to JSON conversion by default.

Conclusion #

The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.