But it does become worse if you have lots of classes you want to serialize. You need to write a default function somewhere that knows about all of your classes:

Somehow I didn't think of this until now, but when I've needed to use JSON to serialize a non-trivial hierachy of types, I' essentially built my own system for doing so. The system builds a "json-compatible dict", and then passes that off to json.dump[s]. Somehow it never dawned on my to try to use the json module's default feature to do this.

And now that I am thinking about, I'm glad I didn't. After all the, hard work is creating the custom JSON compatible data structures. and default really doesn't help with that at all. And this way I can use the exact same code to pass off to ANY json serializer, and indeed, an OTHER serializer that supports the same data structures.

Adding a __json__ protocol would make it a tad more useful (and more so if other json libs supported it) but I'd still need to write essentially the same code, so I think I'd still rather keep the "make it JSON compatible" separate from the JSON serializer itself.

And this is also reinforcing my opinion that the json module should support ONLY serializing JSON itself, and not any "JSON like" form. Whether in NEEDS to enforce that is up in the air, but I think a focused domain is the way to go.

Which means that Adding the ability to serialize Decimal is the only addition needed.

- CHB
 
--
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython