0

有没有办法在不使用自定义编码器的情况下序列化 python 类?我尝试了以下方法,但出现错误:TypeError: hello is not JSON serializable 这很奇怪,因为“hello”是一个字符串。

class MyObj(object):

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

    def __repr__(self):
        return self.address 

x = MyObj("hello")

print json.dumps(x)

输出应该很简单

"hello"
4

2 回答 2

1

jsonpickle怎么样?

jsonpickle 是一个 Python 库,用于将复杂的 Python 对象与 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"}'
于 2013-08-31T19:49:42.107 回答
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))

输出

>>> 
{"address": "hello"}
["hello"]
于 2013-08-31T20:55:33.610 回答