关于python:如何使JSON对象可序列化

How to make a JSON object serializable

本问题已经有最佳答案,请猛点这里访问。

有没有一种方法可以在不使用自定义编码器的情况下序列化Python类?我尝试过以下方法,但我得到了错误:typeerror:hello不是JSON可序列化的,这很奇怪,因为"hello"是一个字符串。

1
2
3
4
5
6
7
8
9
10
11
class MyObj(object):

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

    def __repr__(self):
        return self.address

x = MyObj("hello")

print json.dumps(x)

输出应该简单

1
"hello"


杰森皮克怎么样?

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

1
2
3
4
5
6
7
8
9
>>> 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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))

输出

1
2
3
>>>
{"address":"hello"}
["hello"]