0

I am aware I can use a JSON encoder to make my custom class serializable. But is it possible for me to edit my custom class so it is compatible with json.dump()?

For example can I just implement a method on the class that is called by json.dumps() like this...

class GroundTruthEle:
    def __init__(self, path, gt):
        self.path = path
        self.ground_truth = gt
        self.results = [{
            'params': {},
            'result': [],
            'accuracy': -1
        }]

    def __json__(self):
        return self.__dict__

gt = GroundTruthEle('../images', ((255,0,0)...))

# Will json.dump call gt.__json__()?
json.dump(gt, outfile, ensure_ascii=False)
sazr
  • 24,984
  • 66
  • 194
  • 362
  • 2
    No, there is not hook for this in the data model – juanpa.arrivillaga Jun 21 '19 at 22:44
  • @juanpa.arrivillaga thanks, seems crazy they wouldn't design the python json library to allow for this. – sazr Jun 21 '19 at 22:47
  • Have you looked at [Making object JSON serializable with regular encoder](https://stackoverflow.com/questions/18478287/making-object-json-serializable-with-regular-encoder/18561055#18561055)? – martineau Jun 21 '19 at 22:49
  • @sazr I think that the standard library json encoder wasn't added until relatively late, and changes to the data model are generally slow, plus probably just not deemed worth it in this case – juanpa.arrivillaga Jun 21 '19 at 22:50

0 Answers0