How to make a Python class serializable?
A simple class:
class FileItem: def __init__(self, fname): self.fname = fname
What should I do to be able to get output of:
>>> import json >>> my_file = FileItem('/foo/bar') >>> json.dumps(my_file) TypeError: Object of type 'FileItem' is not JSON serializable
Without the error
The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.
Serialization is the process of encoding the from naive data type to JSON format. The Python module json converts a Python dictionary object into JSON object, and list and tuple are converted into JSON array, and int and float converted as JSON number, None converted as JSON null.
Here is a simple solution for a simple feature:
.toJSON()
MethodInstead of a JSON serializable class, implement a serializer method:
import json class Object: def toJSON(self): return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)
So you just call it to serialize:
me = Object() me.name = "Onur" me.age = 35 me.dog = Object() me.dog.name = "Apollo" print(me.toJSON())
will output:
{ "age": 35, "dog": { "name": "Apollo" }, "name": "Onur" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With