有这样一个需求:
需要一个json 文件 数据从数据库里查询出来
1. 设置文件头
# -*- coding:utf-8 -*-
2. 连接数据库 将数据库连接数据库的编码设置为utf8
db = MySQLdb.connect(host='数据库,user=用户名,passwd=密码,db='数据库, init_command="set names utf8" )
3. 查询出来的数据转化为json
t = json.dumps(r, ensure_ascii=False)
如果 不加 ensure_ascii=False 输出的 t 如果有汉字的话都默认给转换成一堆编码 如果加上的话 就都能正常显示变成了汉字
不加的话: t = json.dumps(r)
[{"category": {"label": "\u65b0\u8f66"}, "title": "\u5168\u65b0\u8d77\u4e9a\u798f\u745e\u8fea\u8def\u8bd5\u8c0d\u7167\u66dd\u5149 \u6216\u4e3a\u5b9a\u540dK3", "url": "http://auto.sohu.com/20120523/n343878794.shtml", "source": "\u641c\u72d0\u6c7d\u8f66", "time": 1337740004, "imgUrl": ""}, {"category": {"label": "\u65b0\u8f66"}, "title": &#