【问题标题】:json encoding issue in PythonPython中的json编码问题
【发布时间】:2016-09-06 07:56:00
【问题描述】:

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

#!/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

默认字典显示成功,但是当自定义encode作为cls参数传递时,出现错误。 对错误原因有何建议?

【问题讨论】:

  • 错字? defualt() 应该是 default()
  • @dhke 正是这样。修正错字OP,它工作正常。
  • 太好了,谢谢,还不够小心!

标签: json python-3.x encoding


【解决方案1】:

这是defUAlt --&gt; 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 上实时查看。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2011-11-04
    相关资源
    最近更新 更多