# 堆代码 duidaima.com def main(request): sql = "SELECT id,title FROM novel LIMIT 10;" result = mysql.getAll(sql) context = {'novel_list': result} return render(request, 'novel_list.html', context)页面输出:
{% for novel in novel_list %} <a href="/chapter/{{novel.id}} "><li>{{ novel.title }}</li></a> {% endfor %}如果不加任何转换,页面上显示的中文将会是字节码。
import json dict = {'id': 1, 'title': b'\xe7\xac\xac\xe4\xb8\x80\xe7\xab\xa0 \xe7\xa7\xa6\xe7\xbe\xbd'} dup = json.dumps(dict ,ensure_ascii=False) print(dup)Python2执行输出:
{"id": 1, "title": "第一章 秦羽"}Python3执行报错:
TypeError: Object of type bytes is not JSON serializable查询了半天,最终解决方案:
pip3 install numpy最终代码:
import json import numpy as np // 堆代码 duidaima.com class MyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, bytes): return str(obj, encoding='utf-8'); return json.JSONEncoder.default(self, obj) dict = {'id': 1, 'title': b'\xe7\xac\xac\xe4\xb8\x80\xe7\xab\xa0 \xe7\xa7\xa6\xe7\xbe\xbd'} dup = json.dumps(dict , cls=MyEncoder, ensure_ascii=False, indent=4) print(dup)你也可以for循环,然后单个转码:
sql = "SELECT id,title FROM novel LIMIT 10;" result = mysql.getAll(sql) for each in result: ach['title'] = each['title'].decode('utf-8')字符串通过编码转换为字节码,字节码通过解码转换为字符串:
str--->(encode)--->bytes,bytes--->(decode)--->str
encode 编码,在已有unicode的情况下,转码为其它编码,比如 u.encode('utf-8'),结果为utf-8
def main(request): sql = "SELECT id,title FROM novel LIMIT 10;" result = mysql.getAll(sql) # 转Json对象 result = json.dumps(result, cls=MyEncoder, ensure_ascii=False, indent=4) # 转字典类型 result = json.loads(result) context = {'novel_list': result} return render(request, 'novel_list.html', context)参数详解
json.dumps(result, cls=MyEncoder, ensure_ascii=False, indent=4)indent
{ "id": 1, "title": "\u7b2c\u4e00\u7ae0 \u79e6\u7fbd" }cls
TypeError: Object of type bytes is not JSON serializable
最终解决方案
由于系统读取数据用的是 PooledDB 数据库连接池,我们只需要把参数 use_unicode 设置为 False 使用系统编码即可。