简体   繁体   English

如何在python中json序列化对象

[英]how to json serialize objects in python

Does python support random json serialization? python是否支持随机json序列化? I get this error: 我收到此错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "commands.py", line 36, in toJson
    return json.dumps(self)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 178, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <commands.SampleCommand object at 0x105d957d0> is not JSON serializable

Snippet: 片段:

class SampleCommand(Command):
    def __init__(self,message=None):
        super(Command, self).__init__()
        pass

    def parse(self):
        pass

    def toJson(self):
        return json.dumps(self)

json within python by default can only handle certain objects like dictionaries, list and basic types such as ints, strings and so on for more complex types you need to define your own serialization scheme 默认情况下,python中的json只能处理某些对象,如字典,列表和基本类型,如整数,字符串等,以便您需要定义自己的序列化方案的更复杂类型

>>> help(json)
Extending JSONEncoder::

    >>> import json
    >>> class ComplexEncoder(json.JSONEncoder):
    ...     def default(self, obj):
    ...         if isinstance(obj, complex):
    ...             return [obj.real, obj.imag]
    ...         return json.JSONEncoder.default(self, obj)
    ...
    >>> dumps(2 + 1j, cls=ComplexEncoder)
    '[2.0, 1.0]'
    >>> ComplexEncoder().encode(2 + 1j)
    '[2.0, 1.0]'
    >>> list(ComplexEncoder().iterencode(2 + 1j))
    ['[', '2.0', ', ', '1.0', ']']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM