json序列化中文python_json序列化中文及日期时间

1. 中文显示Unicode

python的json.dumps方法默认会输出unicode类型。

解决方法

要输出中文需要指定ensure_ascii参数为False

2. 序列化日期时间出错

使用python自带的json.dumps方法转换数据为json的时候,如果格式化的数据中有datetime类型的数据时会报错

TypeError: datetime.datetime(2014, 03, 20, 12, 10, 44) is not JSON serializable

官方文档中关于json.dumps方法的一个参数(cls)说明:

To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

扩展了一个JSONEncoder出来用来格式化时间

from datetime import datetime, date

import json

class CJsonEncoder(json.JSONEncoder):

def default(self, obj):

if isinstance(obj, datetime):

return obj.strftime('%Y-%m-%d %H:%M:%S')

elif isinstance(obj, date):

return obj.strftime('%Y-%m-%d')

else:

return json.JSONEncoder.default(self, obj)

# 使用

json.dumps(cursor.fetchall(), indent=2, cls=CJsonEncoder, ensure_ascii=False)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值