0

How can I serialize an object that contains a list of other objects?

import json


class Foo:
  def __init__(self, x, y):
    self.x = x
    self.y = y

class Bar:
  def __init__(self):
    self.z = 0
    self.foos = []

bar = Bar()
bar.foos.append(Foo(1, 2))

print(json.dumps(bar.__dict__))

Output

TypeError: <__main__.Foo instance at 0x024DD5F8> is not JSON serializable
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

0 Answers0