You can specify the default
named parameter in the json.dumps()
function:
json.dumps(obj, default=lambda x: x.__dict__)
Explanation:
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
(Works on Python 2.7 and Python 3.x)
Note: In this case you need instance
variables and not class
variables, as the example in the question tries to do. (I am assuming the asker meant class instance
to be an object of a class)
I learned this first from @phihag's answer here. Found it to be the simplest and cleanest way to do the job.