python的json模块通常用于与序列化数据,如
def get_user_info(user_id):
res = {"user_id": 190013234,"nick": "havana"}
json_str = json.dumps(res)
return json_str
但是当要序列化的数据里面包含中文字符时,会变成这样
import json
res = {"user_id": 190027134, "nick": "愚蠢的萝卜"}
print(json.dumps(res))
# {"nick": "u611au8822u7684u841du535c", "user_id": 190027134}
解决办法: 在json.dumps()里面加入一个参数ensure_ascii=False
import json
res = {"user_id": 190027134, "nick": "愚蠢的萝卜"}
print(json.dumps(res))
# {"nick": "愚蠢的萝卜", "user_id": 190027134}
这里有一个问题,如果json的结构很复杂,输出的结果就会很乱,不清晰,这是可以加入一个参数使其格式化
import json
res = {"user_id": 190027134, "nick": "愚蠢的萝卜"}
print(json.dumps(res))
# {
"nick": "愚蠢的萝卜",
"user_id": 190027134
}
如果序列化的数据里面有python的datetime.datetime类型,那么序列化会报错
import datetime
res = {"user_id": 190027134, "nick": "愚蠢的萝卜", "reg_ts": datetime.datetime.now()}
print(json.dumps(res, ensure_ascii=False, indent=4))
#TypeError: datetime.datetime(2019, 11, 3, 19, 8, 45, 987000) is not JSON serializable
解决办法是使用自定义的jsonencoder代替原生的jsonencoder
class DatetimeEncoder(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)
res = {"user_id": 190027134, "nick": "愚蠢的萝卜", "reg_ts": datetime.datetime.now(), "last_login_date": datetime.date.today()}
print(json.dumps(res, ensure_ascii=False, indent=4, cls=DatetimeEncoder))
# {
"nick": "愚蠢的萝卜",
"user_id": 190027134,
"reg_ts": "2019-11-03 20:09:55",
"last_login_date": "2019-11-03"
}