专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

python json.dumps()日期错误、输出中文为\uxxxx问题解决

在使用json.dumps时要注意一个问题

json.dumps(result, cls=json_helper.CJsonEncoder,ensure_ascii=False)

TypeError: Object of type ‘datetime’ is not JSON serializable 解决方法

解决日期错误,自定义日期检测:json_helper.py

#!/usr/bin/env python
# coding=utf-8

import json
import datetime

class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)

TypeError: Object of type ‘bytes’ is not JSON serializable

是因为json.dumps函数发现字典里面有bytes类型的数据,因此无法编码,只要在编码函数之前写一个编码类就行了,只要检查到了是bytes类型的数据就把它转化成str类型。因此可以自己写一个encoder去继承jsonencoder ,这样就能够进行编码了。

TypeError: Object of type ‘ndarray’ is not JSON serializable

这样也是一样的处理方式,当检查到了ndarray数据,把它转化成list数据就行

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        else:
            return json.JSONEncoder.default(self, obj)

中文为\uxxxx问题

#

import json print json.dumps(‘中国’) “\u4e2d\u56fd”

输出的会是 ‘中国’ 中的ascii 字符码,而不是真正的中文。

这是因为json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False:

import json print json.dumps(‘中国’) “\u4e2d\u56fd”

print json.dumps(‘中国’,ensure_ascii=False) “中国”

文章永久链接:https://tech.souyunku.com/42036

未经允许不得转载:搜云库技术团队 » python json.dumps()日期错误、输出中文为\uxxxx问题解决

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们