背景
python内置库json序列化支持的数据类型不多,经常在使用dumps
函数时遇到对象不支持序列化的情况,在json库的encoder.py
文件中有如下说明
Extensible JSON <http://json.org> encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str | string |
+-------------------+---------------+
| int, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
``.default()`` method with another method that returns a serializable
object for ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
解决方案
在使用内置json序列化函数前,可以预处理序列化对象
import json
def jsonPrepare(data, encoding='utf8'):
# 不处理
if data is None or data is True or data is False:
return data
if isinstance(data, int) or isinstance(data, float) or isinstance(data, str):
return data
# 遍历处理
if isinstance(data, list) or isinstance(data, set) or isinstance(data, tuple):
return list([jsonPrepare(i, encoding=encoding) for i in data])
elif isinstance(data, dict):
return {
jsonPrepare(k, encoding=encoding): jsonPrepare(v, encoding=encoding) for k, v in data.items()}
# 解码
elif isinstance(data, bytes):
return data.decode(encoding=encoding)
else:
return str(data)
data = json.dumps(jsonPrepare(data))