0

Is there a way to serialize a python class without using a custom encoder? I've tried the following approach but I get the error: TypeError: hello is not JSON serializable which is strange since "hello" is a string.

class MyObj(object):

    def __init__(self, address):
        self.address = address

    def __repr__(self):
        return self.address 

x = MyObj("hello")

print json.dumps(x)

The output should be simply

"hello"
Roberto
  • 1,281
  • 3
  • 16
  • 23

2 Answers2

1

How about jsonpickle?

jsonpickle is a Python library for serialization and deserialization of complex Python objects to and from JSON.

>>> class MyObj(object):
...     def __init__(self, address):
...         self.address = address
...     def __repr__(self):
...         return self.address 
... 
>>> x = MyObj("hello")
>>> jsonpickle.encode(x)
'{"py/object": "__main__.MyObj", "address": "hello"}'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    The json output is part of a restful API and and such I need to carefully control the format. In this example the output should be simply "hello". – Roberto Aug 31 '13 at 20:14
0
import json

class MyObj(object):

    def __init__(self, address):
        self.address = address

    def __repr__(self):
        return self.address

    def serialize(self, values_only = False):
        if values_only:
            return self.__dict__.values()
        return self.__dict__

x = MyObj("hello")

print json.dumps(x.serialize())
print json.dumps(x.serialize(True))

output

>>> 
{"address": "hello"}
["hello"]
blakev
  • 4,154
  • 2
  • 32
  • 52
  • 1
    This does not work if the object is inside another structure like a dictionary, like foo = { 'obj' : x } and then json.dumps(foo) – Roberto Sep 01 '13 at 08:40