TypeError: Object of type method is not JSON serializable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: Object of type method is not JSON serializable #

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

Here is an example of how the error occurs.

main.py
import json class Employee(): def get_salary(self): return 100 emp = Employee() # ⛔️ TypeError: Object of type method is not JSON serializable json_str = json.dumps({'salary': emp.get_salary}) # 👈️ forgot to call method

We forgot to call the emp.get_salary() method in the call to the json.dumps() method.

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

main.py
import json class Employee(): def get_salary(self): return 100 emp = Employee() # ✅ call method emp.get_salary() and NOT emp.get_salary json_str = json.dumps({'salary': emp.get_salary()}) print(json_str) # 👉️ '{"salary": 100}' print(type(json_str)) # 👉️ <class 'str'>

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

We called the method, so we serialized the int, rather than trying to serialize the method itself.

You have to add parentheses to call a method, e.g. emp.get_salary(), otherwise we pass a reference to the emp.get_salary method 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 method to JSON conversion by default.

Conclusion #

The Python "TypeError: Object of type method is not JSON serializable" occurs when we try to serialize a method to JSON. To solve the error, make sure to call the method and serialize the object that the method 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.