2

Does python support random json serialization? I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "commands.py", line 36, in toJson
    return json.dumps(self)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 178, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <commands.SampleCommand object at 0x105d957d0> is not JSON serializable

Snippet:

class SampleCommand(Command):
    def __init__(self,message=None):
        super(Command, self).__init__()
        pass

    def parse(self):
        pass

    def toJson(self):
        return json.dumps(self)
ssk
  • 9,045
  • 26
  • 96
  • 169
  • 2
    http://stackoverflow.com/questions/1458450/python-serializable-objects-json and http://stackoverflow.com/questions/3768895/python-how-to-make-a-class-json-serializable. – user545424 Jun 24 '12 at 02:53

1 Answers1

10

json within python by default can only handle certain objects like dictionaries, list and basic types such as ints, strings and so on for more complex types you need to define your own serialization scheme

>>> help(json)
Extending JSONEncoder::

    >>> import json
    >>> class ComplexEncoder(json.JSONEncoder):
    ...     def default(self, obj):
    ...         if isinstance(obj, complex):
    ...             return [obj.real, obj.imag]
    ...         return json.JSONEncoder.default(self, obj)
    ...
    >>> dumps(2 + 1j, cls=ComplexEncoder)
    '[2.0, 1.0]'
    >>> ComplexEncoder().encode(2 + 1j)
    '[2.0, 1.0]'
    >>> list(ComplexEncoder().iterencode(2 + 1j))
    ['[', '2.0', ', ', '1.0', ']']
Samy Vilar
  • 10,800
  • 2
  • 39
  • 34
  • You should point explicitly that your code is an example of extending the JSONEncoder to add the ability to serialize python "complex numbers" into JSON. – Felix Jun 24 '12 at 05:23
  • @FelixBonkoski note the `>>> help(json)` this is nothing more then taken right from the docs, I was trying to emphasize that if you are interesting/stuck in a python module the first step is to call `help` – Samy Vilar Jun 24 '12 at 05:37