Python 如何使JSON对象可序列化

Python 如何使JSON对象可序列化,python,json,serialization,Python,Json,Serialization,有没有一种方法可以在不使用自定义编码器的情况下序列化python类?我尝试了以下方法,但得到了错误:TypeError:hello不是JSON可序列化的,这很奇怪,因为“hello”是一个字符串 class MyObj(object): def __init__(self, address): self.address = address def __repr__(self): return self.address x = MyObj("

有没有一种方法可以在不使用自定义编码器的情况下序列化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"
怎么样

jsonpickle是一个用于序列化和反序列化的Python库 从JSON到JSON的复杂Python对象

输出

>>> 
{"address": "hello"}
["hello"]

json输出是restful API的一部分,因此我需要仔细控制格式。在本例中,输出应该是简单的“hello”。如果对象位于另一个结构(如字典,如foo={'obj':x}),然后是json.dumps(foo),则这不起作用
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"]