11

I have a custom class, let's call is class ObjectA(), and it have a bunch of functions, property, etc.., and I want to serialize object using the standard json library in python, what do I have to implement that this object will serialize to JSON without write a custom encoder?

Thank you

code base 5000
  • 3,812
  • 13
  • 44
  • 73
  • Probably a dupe of this question: http://stackoverflow.com/questions/3768895/python-how-to-make-a-class-json-serializable – dano Apr 15 '14 at 15:56

1 Answers1

12

Subclass json.JSONEncoder, and then construct a suitable dictionary or array.

See "Extending JSONEncoder" behind this link

Like this:

>>> class A:  pass
... 
>>> a = A()
>>> a.foo = "bar"
>>> import json
>>> 
>>> class MyEncoder(json.JSONEncoder):
...    def default(self, obj):
...       if isinstance(obj, A): 
...          return { "foo" : obj.foo }
...       return json.JSONEncoder.default(self, obj)
... 
>>> json.dumps(a, cls=MyEncoder)
'{"foo": "bar"}'
FrobberOfBits
  • 17,634
  • 4
  • 52
  • 86
  • 5
    Not possible without a custom encoder. If the premise of the question is that json doesn't already know how to encode it, then any solution will involve a custom encoder. Maybe not one that extends JSONEncoder - you could write a simple f() that maps an object onto a dict - but what would that be, if not a custom encoder? – FrobberOfBits Apr 15 '14 at 16:02
  • Should mention that in your answer so OP knows it's not possible, and what the other options (if any) there are. Sorry if I came off a bit rude. – Ford Apr 15 '14 at 16:27
  • 1
    Seems a bit weak that you can't do this without a custom encoder. I would think you could implement __dict__() or something like that and the JSON library would know how to handle it. I wanted to avoid custom encoders. I have about 30 custom classes. – code base 5000 Apr 17 '14 at 15:33
  • 1
    If you implemented __dict__() and turned it into some custom dictionary...that would be a custom encoder. You just would have chosen to implement it in that way. If the library doesn't automagically know how to convert your objects, then any extra code you write for that purpose is going to be a custom encoder by some other name. – FrobberOfBits Apr 17 '14 at 16:06
  • 4
    @FrobberOfBits the difference between implementing a `__dict__` method and a custom encoder is, that I can pass my object implementing `__dict__` to a module which is already using the json library and it would accept it without throwing a "could not serialize" error. While I can not change the encoder this module is using. This is a world of a difference. Rust really has the right idea with their trait system... use case: custom configuration class, passed to `databaseClient.add_table()` – Felix B. Sep 01 '20 at 19:17
  • @FelixB. You also do not have to now write, use and maintain a new wrapper. – Chris Jan 04 '22 at 22:22
  • The default encoder should try executing obj.__json__(). They just did a bad job writing the standard library – segfault Jun 22 '22 at 15:17