【python】python 转换为json时候 汉字编码问题
来源:互联网 发布:松下plc编程实例 编辑:程序博客网 时间:2024/05/18 07:51
simplejson官网doc:http://simplejson.googlecode.com/svn/tags/simplejson-2.1.1/docs/index.html
有这样一个需求:
需要一个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
python 的api是这样解释的:
- If ensure_ascii is False (default: True), then some chunks written to fp may be unicode instances, subject to normal Python str to unicode coercion rules. Unless fp.write() explicitly understands unicode (as in codecs.getwriter()) this is likely to cause an error.
PS : e文不好 就不再这里误导了。
如果 不加 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": "\u65b0\u5965\u8feaQ7/Q8\u66f4\u591a\u4fe1\u606f\u66dd\u5149 \u5c06\u57fa\u4e8eMLB\u5e73\u53f0", "url": "http://auto.sohu.com/20120523/n343873150.shtml", "source": "\u641c\u72d0\u6c7d\u8f66", "time": 1337737913, "imgUrl": ""}]
加上的话: t = json.dumps(r, ensure_ascii=False)
- [{"category": {"label": "新车"}, "title": "全新起亚福瑞迪路试谍照曝光 或为定名K3", "url": "http://auto.sohu.com/20120523/n343878794.shtml", "source": "汽车", "time": 1337740004, "imgUrl": ""}, {"category": {"label": "新车"}, "title": "新奥迪Q7/Q8更多信息曝光 将基于MLB平台", "url": "http://auto.sohu.com/20120523/n343873150.shtml", "source": "汽车", "time": 1337737913, "imgUrl": ""}]
- python 转换为json时候 汉字编码问题
- 【python】python 转换为json时候 汉字编码问题
- python汉字编码的问题
- python汉字编码
- python汉字编码
- python 汉字编码
- python中将json字符串转换为dict
- Python 操作xml转换为json格式
- python 如何将CSV转换为json
- python----mysql链接汉字编码的问题
- python 爬虫过程中汉字编码的问题
- Python中json数据转换问题
- Python汉字编码经验总结
- Python汉字编码经验总结
- python编码问题:\ufeff8804转换为8804
- python json 数据转换
- python对象json转换
- 一个Excel转换为Json格式的Python脚本
- Poj 1251 Jungle Roads -- 最小生成树
- 【PAT】1051. Pop Sequence (25)
- 香梨股份 600506 2013-08-27
- 查找二叉树中的最大距离
- Hoj 3133 White-box testing
- 【python】python 转换为json时候 汉字编码问题
- 软件编码规范
- HMM 做训练的 Sigma not positive definite (非正定的)原因及处理办法
- Java中的main线程是不是最后一个退出的线程
- n支队伍比赛,分别编号为0,1,2。。。。n-1,已知它们之间的实力对比关系, 存储在一个二维数组w[n][n]中,w[i][j] 的值代表编号为i,j 的队伍中更强的一支。
- 求1+2+3+...+n
- hashSet根据compareTo()方法的写法不同,hashSet是可以加入重复元素的(即使这2个元素的hashCode相同)。
- DOM编程之一
- VMware下扩展硬盘空间 fdisk命令详解