You can serialise the __dict__
attribute of m
:
In [214]: json.dumps(m.__dict__)
Out[214]: '{"quadruple": 400, "double": 200, "triple": 300}'
You can also call vars:
In [216]: json.dumps(vars(m))
Out[216]: '{"quadruple": 400, "double": 200, "triple": 300}'
What to use and why:
Use `__dict__` or `vars()`?
For more complicated classes, consider the use of jsonpickle.
jsonpickle
is a Python library for serialization and deserialization
of complex Python objects to and from JSON. The standard Python
libraries for encoding Python into JSON, such as the stdlib’s json
,
simplejson
, and demjson
, can only handle Python primitives that have a
direct JSON equivalent (e.g. dict
s, list
s, str
ings, int
s, etc.).
jsonpickle
builds on top of these libraries and allows more complex
data structures to be serialized to JSON.
Emphasis mine.