Sometimes, we want to JSON serialize sets with Python.
In this article, we’ll look at how to JSON serialize sets with Python.
How to JSON serialize sets with Python?
To JSON serialize sets with Python, we can use the json.dumps
method with a custom json.JSONEncoder
subclass.
For instance, we write
import json
class SetEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return json.JSONEncoder.default(self, obj)
s = json.dumps(set([1,2,3,4,5]), cls=SetEncoder)
to create the SetEncoder
class which is subclass of the json.JSONEncoder
class.
In it, we add the default
method.
And in the default
method, we return the set
converted to a list if the obj
object is a set
.
And then we call json.JSONEncoder.default(self, obj)
to serialize the obj
object.
Next, we call json.dumps
with a set and the cls
argument set to SetEncoder
to use SetEncoder
to serialize the set into a JSON string.
Conclusion
To JSON serialize sets with Python, we can use the json.dumps
method with a custom json.JSONEncoder
subclass.