When dealing with the JSON format in Python, one error that you might encounter is:
TypeError: Object of type set is not JSON serializable
This error commonly occurs when you try to convert a set
object into a JSON string.
The following tutorial shows an example that causes this error and how to fix it.
How to reproduce this error
Suppose you have a set
object called x
as follows:
x = {1, 2, 3}
Next, you try to convert the x
variable into a JSON string using the json.dumps()
method as follows:
import json
x = {1, 2, 3}
json_str = json.dumps(x)
You’ll get a similar error message output like this:
Traceback (most recent call last):
File "main.py", line 5, in <module>
json_str = json.dumps(x)
File ...
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable
This error means that the JSON encoder doesn’t know how to serialize the x
object into a JSON string.
How to fix this error: 1. Convert set to list
To resolve this error, you can convert the set
object into a list
, which is supported by the json
module.
Use the list()
method as follows:
import json
x = {1, 2, 3}
json_str = json.dumps(list(x))
print(json_str) # [1, 2, 3]
The set
object is converted into a list
object before being encoded as a JSON string.
2. Extend the JSONEncoder
class
If you have many set
objects that you need to convert to JSON string, you can extend the JSON encoder class and define how to handle a set
object there.
To create a custom JSON encoder, you need to extend the JSONEncoder
class as follows:
import json
class SetEncoder(json.JSONEncoder):
def default(self, obj):
return list(obj)
Anytime you call the json.dumps()
method, pass the SetEncoder
class above as the value of cls
keyword argument as follows:
x = {1, 2, 3}
json_str = json.dumps(x, cls=SetEncoder)
print("JSON string:", json_str) # [1, 2, 3]
decoded_set = json.loads(json_str)
print("Decoded set:", decoded_set) # [1, 2, 3]
But one weakness with this solution is you still convert the set
object into a list
object before encoding it as a JSON string.
If you don’t want to convert the set into a list, you can use the jsonpickle
library, which knows how to convert a set into a JSON string.
3. Using the jsonpickle
library
Install the jsonpickle
library using pip
as follows:
pip install jsonpickle
# For pip3
pip3 install jsonpickle
Next, call the encode()
method to encode a Python object into a JSON string. Use the decode()
method to reverse the conversion:
import jsonpickle
x = {1, 2, 3}
json_str = jsonpickle.encode(x)
print("JSON string:", json_str)
decoded_set = jsonpickle.decode(json_str)
print("Decoded set:", decoded_set)
Output:
JSON string: {"py/set": [1, 2, 3]}
Decoded set: {1, 2, 3}
As you can see, the jsonpickle()
module inherently converts the set
object into a list-like structure and added the key "py/set"
to the string.
This JSON format allows the library to decode it back to Python set
object without any issue.
More resources
The following tutorials explain how you can fix other common errors when using the json
library:
Object of type ‘int64’ is not JSON serializable
Object of type ndarray is not JSON serializable
I hope the tutorials are helpful. Until next time! 👍