Each object’s class to be stored in JSON in a convenient for viewing way must have the __repr__ function, which returns the text representation of the object.
1 2 3 4 5 6 7 8 |
class TestObj: def __init__(self, x, y): self.__x = x self.__y = y def __repr__(self): return "TestObj({x},{y})".format(x = self.__x, y = self.__y) |
The dictionary with objects:
1 |
datadict = {"group": {"Object1": TestObj(10,22), "Object2": TestObj(36,74)}} |
Saving the dictionary to JSON:
1 2 3 4 |
with open("c:/file.json", "w", encoding="utf-8") as file: import pprint pprint.pprint(datadict, indent=4, stream=file) file.close() |