TypeError: Object of type function is not JSON serializable

avatar

Borislav Hadzhiev

Wed Apr 20 20221 min read

banner

Photo by Tarah Dane

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 parenthesis 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.