Python如果要将一个字典数据转化为Json格式,对数据类型有一定的要求,默认支持:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str | string |
+-------------------+---------------+
| int, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
如果要支持其他的类型,需要自定义JSONEncoder
才能实现。例如:
import json
from decimal import Decimal
from datetime import datetime
data = [
{"id": 1, "name": "tom", "age": 1, 'size': Decimal("9.3"), 'ctime': datetime.now()},
{"id": 2, "name": "jerry", "age": 2, 'size': Decimal("0.5"), 'ctime': datetime.now()},
]
res = json.dumps(data)
print(res)
输出结果显示报错:
TypeError: Object of type Decimal is not JSON serializable
原因就是Decimal
不能被序列化。
解决办法是实现json.JSONEncoder
,
import json
from decimal import Decimal
from datetime import datetime
data = [
{"id": 1, "name": "tom", "age": 1, 'size': Decimal("9.3"), 'ctime': datetime.now()},
{"id": 2, "name": "jerry", "age": 2, 'size': Decimal("0.5"), 'ctime': datetime.now()},
]
class MyJSONEncoder(json.JSONEncoder):
def default(self, o):
if type(o) == Decimal: # 当原始数据中的数据类型为Decimal
return str(o)
elif type(o) == datetime: # 当原始数据中的数据类型为Decimal
return o.strftime("%Y-%M-%d") # 只获取年月日, 并转为字符串
return super().default(o)
res = json.dumps(data, cls=MyJSONEncoder)
print(res)
其中的type(o)
表示,json数据中的所有的数据类型。