Object of type dict_values is not JSON serializable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Object of type dict_values is not JSON serializable #

The Python "TypeError: Object of type dict_values is not JSON serializable" occurs when we try to convert a dict_values object to JSON. To solve the error, pass the dict_values object to the list() class before the conversion to JSON.

Here is an example of how the error occurs.

main.py
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps(my_dict.values())

We tried passing a dict_values object to the json.dumps() method but the method doesn't handle dict_values objects by default.

To solve the error, pass the dict_values object to the list class before serializing it to JSON.

main.py
import json my_dict = {'name': 'Alice', 'age': 30} # ✅ convert list values to list json_str = json.dumps(list(my_dict.values())) print(json_str) # 👉️ '["Alice", 30]' print(type(json_str)) # 👉️ '<class 'str'>'
Note that you can remove the call to the values() method if you meant to serialize the entire dict object to JSON.

The example converts the dict_values object to a list when serializing to JSON.

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

The dict.values method returns a new view of the dictionary's values.

Alternatively, you can extend from the JSONEncoder class and handle the conversions in a default method.

main.py
import json from collections import abc class DictValuesEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, abc.ValuesView): return list(obj) return json.JSONEncoder.default(self, obj) my_dict = {'name': 'Alice', 'age': 30} json_str = json.dumps(my_dict.values(), cls=DictValuesEncoder) print(json_str) # 👉️ '["Alice", 30]' print(type(json_str)) # 👉️ <class 'str'>

We extended from the JSONEncoder class.

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

Notice that the JSONEncoder class doesn't support dict_values to JSON conversion by default.

We can handle this by extending from the class and implementing a default() method that returns a serializable object.

main.py
import json from collections import abc class DictValuesEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, abc.ValuesView): return list(obj) return json.JSONEncoder.default(self, obj)

If the passed in value is a dict_values object, we convert it to a list and return the result.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

In all other cases, we let the base classes' default method do the serialization.

To use a custom JSONEncoder, specify it with the cls keyword argument in your call to the json.dumps() method.

main.py
import json from collections import abc class DictValuesEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, abc.ValuesView): return list(obj) return json.JSONEncoder.default(self, obj) my_dict = {'name': 'Alice', 'age': 30} # ✅ pass cls kwarg json_str = json.dumps(my_dict.values(), cls=DictValuesEncoder) print(json_str) # 👉️ '["Alice", 30]' print(type(json_str)) # 👉️ <class 'str'>

If you don't provide the cls kwarg, the default JSONEncoder is used.

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.