How can I serializing a class into JSON?
Posted: Tue May 28, 2024 9:35 pm
I am trying to create a JSON string representation of a class instance and having difficulty. Let's say the class is built like this:
A call to the json.dumps is made like this:
It is failing and telling me that the testclass is not JSON serializable.
I have also tried using the pickle module :
And it gives class instance information but not a serialized content of the class instance.
What am I doing wrong?
Code: Select all
class testclass:
value1 = "a"
value2 = "b"
Code: Select all
t = testclass()
json.dumps(t)
Code: Select all
TypeError: <__main__.testclass object at 0x000000000227A400> is not JSON serializable
Code: Select all
t = testclass()
print(pickle.dumps(t, pickle.HIGHEST_PROTOCOL))
Code: Select all
b'\x80\x03c__main__\ntestclass\nq\x00)\x81q\x01}q\x02b.'