Skip to main content

How to Resolve Python "TypeError: Object of type function/method is not JSON serializable"

When using Python's json.dumps() to serialize objects into JSON strings, you might encounter TypeError: Object of type function is not JSON serializable or TypeError: Object of type method is not JSON serializable. These errors indicate that you've tried to include a function or method object directly within the data structure being serialized. JSON is a data-interchange format and cannot represent executable code like functions or methods.

This guide explains why this error occurs and shows the simple solution: call the function/method first and serialize its return value instead.

Understanding the Error: JSON Serializes Data, Not Code

JSON (JavaScript Object Notation) is designed to represent data structures. Its standard types include objects (like Python dictionaries), arrays (like Python lists/tuples), strings, numbers, booleans, and null (like Python's None).

Python functions and methods, on the other hand, represent executable code. They are not simple data values. There's no standard way to represent a Python function or method within the JSON format. Therefore, when json.dumps() encounters a function or method object within the data structure you're trying to serialize, it doesn't know how to convert it and raises the TypeError.

Cause: Passing a Function or Method Object to json.dumps()

The error occurs because the data structure you pass to json.dumps() contains a direct reference to a function or method object itself, rather than the result of calling that function or method.

Forgetting Parentheses () During Call

This is the most common mistake. You intend to include the return value of a function/method in your data, but you forget to add the call parentheses ().

import json

# --- Function Example ---
def get_user_data():
"""Returns user information as a dictionary."""
return {'username': 'alice', 'id': 123}

# Error Scenario: Passing the function itself, not its result
try:
# ⛔️ TypeError: Object of type function is not JSON serializable
# We passed 'get_user_data' (the function object) instead of 'get_user_data()'
data_to_serialize = {'user_info': get_user_data}
json_string = json.dumps(data_to_serialize)
print(json_string)
except TypeError as e:
print(f"Error (Function): {e}")

# --- Method Example ---
class Configuration:
def get_settings(self):
"""Returns settings dictionary."""
return {'theme': 'dark', 'timeout': 30}

config_instance = Configuration()

# Error Scenario: Passing the method itself, not its result
try:
# ⛔️ TypeError: Object of type method is not JSON serializable
# We passed 'config_instance.get_settings' (the method object)
# instead of 'config_instance.get_settings()'
data_to_serialize = {'config': config_instance.get_settings}
json_string = json.dumps(data_to_serialize)
print(json_string)
except TypeError as e:
print(f"\nError (Method): {e}")

In both cases, json.dumps receives the function/method object itself, which it cannot serialize.

Intending to Store Function/Method Reference (Incorrect for JSON)

While you can store references to functions/methods in Python dictionaries, these references cannot be directly serialized into standard JSON. JSON represents data state, not executable code references.

Solution: Call the Function/Method First, Serialize the Result

The fix is straightforward: ensure you call the function or method using parentheses () so that its return value (which should be a JSON-serializable type like a dict, list, string, number, bool, or None) is included in the data structure passed to json.dumps().

Example with a Function

import json

def get_user_data():
"""Returns user information as a dictionary."""
return {'username': 'alice', 'id': 123}

# ✅ Call the function get_user_data() to get the dictionary result
user_dictionary = get_user_data()

# ✅ Serialize the dictionary returned by the function
data_to_serialize = {'user_info': user_dictionary}
json_string = json.dumps(data_to_serialize, indent=2) # Use indent for readability

print(f"JSON output (Function Result):\n{json_string}")
print(f"Type of serialized output: {type(json_string)}")

Output:

JSON output (Function Result):
{
"user_info": {
"username": "alice",
"id": 123
}
}
Type of serialized output: <class 'str'>

We now serialize the dictionary {'username': 'alice', 'id': 123} which json.dumps understands.

Example with a Class Method

import json

class Configuration:
def get_settings(self):
"""Returns settings dictionary."""
return {'theme': 'dark', 'timeout': 30}

config_instance = Configuration()

# ✅ Call the method config_instance.get_settings() to get the dictionary result
settings_dictionary = config_instance.get_settings()

# ✅ Serialize the dictionary returned by the method
data_to_serialize = {'config': settings_dictionary}
json_string = json.dumps(data_to_serialize, indent=2)

print(f"JSON output (Method Result):\n{json_string}")
print(f"Type of serialized output: {type(json_string)}")

Output:

JSON output (Method Result):
{
"config": {
"theme": "dark",
"timeout": 30
}
}
Type of serialized output: <class 'str'>

By calling emp.get_salary(), we pass the integer 100 (which is JSON serializable) to json.dumps().

JSON Serializable Types (Reminder)

Remember, json.dumps() can directly handle these Python types:

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull

Functions and methods are not included in this list.

Conclusion

The TypeError: Object of type function is not JSON serializable or TypeError: Object of type method is not JSON serializable occurs when you try to serialize the function/method object itself instead of its result.

The solution is to ensure you call the function or method using parentheses () before or during the construction of the data structure you pass to json.dumps(). This provides the return value (which should be JSON serializable) to the encoder, rather than the non-serializable function/method object.

# Incorrect: json.dumps({'data': my_function})
# Correct: json.dumps({'data': my_function()})

# Incorrect: json.dumps({'result': my_object.my_method})
# Correct: json.dumps({'result': my_object.my_method()})