Python中的json编码问题

时间:2016-09-06 07:56:01

标签: json python-3.x encoding

我正在尝试自定义编码,但收到错误。以下代码示例生成错误:

#!/usr/bin/python3

import json

class Contact:
  def __init__(self, first, last):
    self.first = first
    self.last = last

  @property
  def full_name(self):
    return ("{} {}".format(self.first, self.last))

class ContactEncoder(json.JSONEncoder):
  def defualt(self, obj):
    if isinstance(obj, Contact):
      return  {"is_contact": 'T'
              ,"first": obj.first
              ,"last": obj.last
              ,"full_name": obj.full_name}
    return super().defualt(obj)

if __name__ == "__main__":
  c = Contact("Jay", "Loophole")
  print(json.dumps(c.__dict__))
  print(json.dumps(c, cls=ContactEncoder))

产生的错误是:

{"first": "Jay", "last": "Loophole"}
Traceback (most recent call last):
  File "json_dump.py", line 26, in <module>
    print(json.dumps(c, cls=ContactEncoder))
  File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.5/json/encoder.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <__main__.Contact object at 0x7ffb3445a400> is not JSON serializable

默认字典已成功显示,但是当自定义编码作为cls参数传递时,会发生错误。 有关错误原因的任何建议吗?

1 个答案:

答案 0 :(得分:0)

以下是defUAlt --> defAUlt更正后的更新代码:

import json

class Contact:
  def __init__(self, first, last):
    self.first = first
    self.last = last

  @property
  def full_name(self):
    return ("{} {}".format(self.first, self.last))

class ContactEncoder(json.JSONEncoder):
  def default(self, obj):
    if isinstance(obj, Contact):
      return  {"is_contact": 'T'
              ,"first": obj.first
              ,"last": obj.last
              ,"full_name": obj.full_name}
    return super().default(obj)

if __name__ == "__main__":
  c = Contact("Jay", "Loophole")
  print(json.dumps(c.__dict__))
  print(json.dumps(c, cls=ContactEncoder))

您可以在this page上查看。