lundi 18 juillet 2016

How to serialize an object that contains a list of other objects [duplicate]

This question already has an answer here:

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

Aucun commentaire:

Enregistrer un commentaire