有没有办法在不使用自定义编码器的情况下序列化python类?我尝试了以下方法,但是我得到了错误:TypeError:hello不是JSON可序列化的,这很奇怪,因为“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"
答案 0 :(得分: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"}'
答案 1 :(得分: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"]