千锋扣丁学堂Python培训之详解JSON中特殊类型进行Encoder

2019-07-15 13:29:45 1275浏览

今天千锋扣丁学堂Python培训老师给大家分享一篇关于详解Python对JSON中的特殊类型进行Encoder,文中通过示例代码介绍的非常详细,首先Python处理JSON数据时,dumps函数是经常用到的,当JSON数据中有特殊类型时,往往是比较头疼的,因为经常会报这样一个错误。



自定义编码类

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
 
import json
from datetime import datetime
 
USER_DATA = dict(
  id = 1, name = 'wxnacy', ts = datetime.now()
)
print(json.dumps(USER_DATA))


Traceback (most recent call last):
 File "/Users/wxnacy/PycharmProjects/study/python/office_module/json_demo/dumps.py", line 74, in <module>
  dumps_encoder()
 File "/Users/wxnacy/PycharmProjects/study/python/office_module/json_demo/dumps.py", line 68, in dumps_encoder
  print(json.dumps(USER_DATA))
 File "/Users/wxnacy/.pyenv/versions/3.6.0/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 231, in dumps
  return _default_encoder.encode(obj)
 File "/Users/wxnacy/.pyenv/versions/3.6.0/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 199, in encode
  chunks = self.iterencode(o, _one_shot=True)
 File "/Users/wxnacy/.pyenv/versions/3.6.0/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 257, in iterencode
  return _iterencode(o, 0)
 File "/Users/wxnacy/.pyenv/versions/3.6.0/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 180, in default
  o.__class__.__name__)
TypeError: Object of type 'datetime' is not JSON serializable

原因在于dumps函数不知道如何处理datetime对象,默认情况下json模块使用json.JSONEncoder类来进行编码,此时我们需要自定义一下编码类。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
 
class CustomEncoder(json.JSONEncoder):
  def default(self, x):
    if isinstance(x, datetime):
      return int(x.timestamp())
    return super().default(self, x)

定义编码类CustomEncoder并重写实例的default函数,对特殊类型进行处理,其余类型继续使用父类的解析。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
 
import json
from datetime import datetime
 
class CustomEncoder(json.JSONEncoder):
  def default(self, x):
    if isinstance(x, datetime):
      return int(x.timestamp())
    return super().default(self, x)
 
USER_DATA = dict(
  id = 1, name = 'wxnacy', ts = datetime.now()
)
print(json.dumps(USER_DATA, cls=CustomEncoder))
# {"id": 1, "name": "wxnacy", "ts": 1562938926}

最后整合起来,将类使用cls参数传入dumps函数即可。

使用CustomEncoder实例的encode函数可以对对象进行转码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
print(CustomEncoder().encode(datetime.now()))
# 1562939035

在父类源码中,所有的编码逻辑都在encode函数中,default只负责抛出TypeError异常,这就是文章开始报错的出处。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
 
def default(self, o):
  """Implement this method in a subclass such that it returns
  a serializable object for ``o``, or calls the base implementation
  (to raise a ``TypeError``).
 
  For example, to support arbitrary iterators, you could
  implement default like this::
 
    def default(self, o):
      try:
        iterable = iter(o)
      except TypeError:
        pass
      else:
        return list(iterable)
      # Let the base class default method raise the TypeError
      return JSONEncoder.default(self, o)
 
  """
  raise TypeError(f'Object of type {o.__class__.__name__} '
          f'is not JSON serializable')
 
def encode(self, o):
  """Return a JSON string representation of a Python data structure.
 
  >>> from json.encoder import JSONEncoder
  >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
  '{"foo": ["bar", "baz"]}'
 
  """
  # This is for extremely simple cases and benchmarks.
  if isinstance(o, str):
    if self.ensure_ascii:
      return encode_basestring_ascii(o)
    else:
      return encode_basestring(o)
  # This doesn't pass the iterator directly to ''.join() because the
  # exceptions aren't as detailed. The list call should be roughly
  # equivalent to the PySequence_Fast that ''.join() would do.
  chunks = self.iterencode(o, _one_shot=True)
  if not isinstance(chunks, (list, tuple)):
    chunks = list(chunks)
  return ''.join(chunks)

单分派装饰器处理对象

CustomEncoder如果处理的对象种类很多的话,需要写多个ifelifelse来区分,这样并不是不行,但是不够优雅,不够pythonic

根据对象的类型不同,而做出不同的处理。刚好有个装饰器可以做到这点,它就是单分派函数functools.singledispatch

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
 
from datetime import datetime
from datetime import date
from functools import singledispatch
 
class CustomEncoder(json.JSONEncoder):
  def default(self, x):
    try:
      return encode(x)
    except TypeError:
      return super().default(self, x)
 
@singledispatch       # 1
def encode(x):
  raise TypeError('Unencode type')
 
@encode.register(datetime) # 2
def _(x):
  return int(x.timestamp())
 
@encode.register(date)
def _(x):
  return x.isoformat()
 
print(json.dumps(dict(dt = datetime.now(), d = date.today()), cls=CustomEncoder))
# {"dt": 1562940781, "d": "2019-07-12"}

1、使用@singledispatch装饰encode函数,是他处理默认类型。同时给他添加一个装饰器构造函数变量。

2、`@encode.register()是一个装饰器构造函数,接收需要处理的对象类型作为参数。用它装饰的函数不需要名字,_`代替即可。

最后提一点,json也可以在命令行中使用

$ echo '{"json": "obj"}' | python -m json.tool
{
  "json": "obj"
}

以上就是关于千锋扣丁学堂Python培训之详解JSON中特殊类型进行Encoder的全部内容,希望对大家的学习有所帮助,最后想要了解更多关于Python和人工智能方面内容的小伙伴,请关注扣丁学堂Python培训官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供权威的Python开发环境搭建视频,Python培训后的前景无限,行业薪资和未来的发展会越来越好的,扣丁学堂老师精心推出的Python视频教程定能让你快速掌握Python从入门到精通开发实战技能。扣丁学堂Python技术交流群:279521237。


扣丁学堂微信公众号                          Python全栈开发爬虫人工智能机器学习数据分析免费公开课直播间


      【关注微信公众号获取更多学习资料】         【扫码进入Python全栈开发免费公开课】



查看更多关于"Python开发资讯"的相关文章>

标签: Python培训 Python视频教程 Python在线视频 Python学习视频 Python培训班

热门专区

暂无热门资讯

课程推荐

微信
微博
15311698296

全国免费咨询热线

邮箱:codingke@1000phone.com

官方群:148715490

北京千锋互联科技有限公司版权所有   北京市海淀区宝盛北里西区28号中关村智诚科创大厦4层
京ICP备12003911号-6   Copyright © 2013 - 2019

京公网安备 11010802030908号