13

New to Python, trying to define a very simple class that will hold a few values, and then get it output into JSON notation.

import json

class Multiple:
    def __init__(self, basis):
            self.double = basis * 2
            self.triple = basis * 3
            self.quadruple = basis * 4


m = Multiple(100)
json.dumps(m)

I was hoping to see something like

{
  "double":"200",
  "triple":"300",
  "quadruple":"400"
}

but instead get an error: "TypeError: <main.Multiple object at 0x0149A3F0> is not JSON serializable"

0

1 Answer 1

21

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. dicts, lists, strings, ints, etc.). jsonpickle builds on top of these libraries and allows more complex data structures to be serialized to JSON.

Emphasis mine.

Sign up to request clarification or add additional context in comments.

10 Comments

beat me for a second , nice answer
@DanielSanchez Next time :)
it is better to use vars
@AzatIbrakov, did not know about vars and had struggle sometimes with that. It is the useful tip of the day, thanks!!
@AzatIbrakov: I disagree with it in the case of __dict__ just because vars’s overloading is icky.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.