An elegant pythonic solution to – TypeError: is not JSON serializable

So if you ever have to deal with python and JSON at the same time, I’m sure you’ve run into this problem at least once.  With Baybo, the typical example of this is failure for json.dumps to successfully coerce Decimal objects into strings (go figure).  Anyways, the solution to the error above is simply:

dictionary = {"key": "val", "foo": Decimal("8.88")}

dict(map(lambda x: isinstance(x[1], Decimal) and (str(x[0]), str(x[1])) or (str(x[0]), x[1]), dictionary.items()))

Let’s break that down a bit

dictionary.items() => [("key", "val"), ("foo", Decimal("8.88"))]

lambda x: lambda x: isinstance(x[1], Decimal) and (str(x[0]), str(x[1])) or (str(x[0]), x[1]) => ("foo", "8.88")

map turns it all into [("key", "val"), ("foo", "8.88")] if it is in fact a Decimal object, otherwise leaves it alone

which we wrap up with a dict() => {"key": "val", "foo": "8.88"} and dump to json

'{"key": "val", "foo": "8.88"}'

voila! problem solved!

edit (2011-01-04): after looking over this again, I would like to comment that one *might* want to keep integers of type int, list of type list, etc. simply mapping everything to a string is a crufty hack at best. I’ve revised the code to adjust for this. isinstance(x[1], Decimal) and (str(x[0]), str(x[1])) or ... the ever useful and-or logic short-circuting which you may be familiar with if you’ve programmed in C or JavaScript.

edit (2015-12-07): Switched from type(foo) == “TypeString” to isinstance(foo, TypeString).

  • German Larrain M

    You should replace `type(x[1]) == “Decimal”` with `isinstance(x[1], Decimal)` because that’s the pythonic way to do type checking

  • Vadim Khaskel

    str(your_array) – do the trick