详解Python对JSON中的特殊类型进行Encoder

 更新时间:2019年07月15日 11:04:17   作者:温欣爸比  
这篇文章主要介绍了详解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 如果处理的对象种类很多的话,需要写多个 if elif else 来区分,这样并不是不行,但是不够优雅,不够 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"
}

参考链接

json

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 使用Python获取字典键对应值的两种方法

    使用Python获取字典键对应值的两种方法

    对于字典通过键获得值非常简单,但通过值获得键则需绕些弯子,下面这篇文章主要给大家介绍了关于如何使用Python获取字典键对应值的相关资料,需要的朋友可以参考下
    2022-04-04
  • 1分钟快速生成用于网页内容提取的xslt

    1分钟快速生成用于网页内容提取的xslt

    这篇文章主要教大家如何1分钟快速生成用于网页内容提取的xslt,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02
  • Python udp网络程序实现发送、接收数据功能示例

    Python udp网络程序实现发送、接收数据功能示例

    这篇文章主要介绍了Python udp网络程序实现发送、接收数据功能,结合实例形式分析了Python使用socket模块进行udp套接字创建、数据收发等相关操作技巧,需要的朋友可以参考下
    2019-12-12
  • python开发的小球完全弹性碰撞游戏代码

    python开发的小球完全弹性碰撞游戏代码

    这篇文章主要介绍了通过python开发的一个小球完全弹性碰撞游戏效果,特分享下
    2013-10-10
  • Python标准库之Math,Random模块使用详解

    Python标准库之Math,Random模块使用详解

    math数学模块和random随机模块是Python常用的标准库之一。本文将详细为大家介绍一下这两个模块的使用方法,需要的小伙伴可以参考一下
    2022-05-05
  • Python字典及字典基本操作方法详解

    Python字典及字典基本操作方法详解

    这篇文章主要介绍了Python字典及字典基本操作方法,结合实例形式详细分析了Python字典的概念、创建、格式化及常用操作方法与相关注意事项,需要的朋友可以参考下
    2018-01-01
  • Python基础实战总结

    Python基础实战总结

    今天要给大家介绍的是Python基础实战,本文主要以举例说明讲解:问题的关键点就是在于构造姓名,学号和成绩,之后以字典的形式进行写入文件。这里准备两个列表,一个姓,一个名,之后使用random库进行随机字符串拼接,得到姓名,需要的朋友可以参考一下
    2021-10-10
  • python爬虫把url链接编码成gbk2312格式过程解析

    python爬虫把url链接编码成gbk2312格式过程解析

    这篇文章主要介绍了python爬虫把url链接编码成gbk2312格式过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • python实现维吉尼亚加密法

    python实现维吉尼亚加密法

    这篇文章主要为大家详细介绍了python实现维吉尼亚加密法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-03-03
  • Python获取图片像素BGR值并生成纯色图

    Python获取图片像素BGR值并生成纯色图

    这篇文章主要介绍了利用Python获取图片像素BGR值,并将其生成纯色图。文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-01-01

最新评论