python json unicode utf-8处理总结

news/2024/7/16 9:03:27

1.直接输出字典中文
在python中经常遇见直接print dict(字典),或者dict转json,但是没有给特定的参数,然后打印json字符串,输出的中文就成了unicode码的情况,如下:

d = {'name': '张三', 'age': '1'}
print d jd = json.dumps(d) print jd 

输出结果为:

{'age': '1', 'name': '\xe5\xbc\xa0\xe4\xb8\x89'}
{"age": "1", "name": "\u5f20\u4e09"} 

这种情况怎么办呢?
要将字典中的中文正确的输出,可以将d转换成json字符串,转换时使用json.dumps(d, ensure_ascii=False, encoding='utf-8'))

d = {'name': '张三', 'age': '1'} print d jd = json.dumps(d, ensure_ascii=False, encoding='utf-8')) print jd 

输出结果为:

{'age': '1', 'name': '\xe5\xbc\xa0\xe4\xb8\x89'}
{"age": "1", "name": "张三"} 

参数ensure_ascii=False不能少, encoding可以省略,因为默认就是encoding='utf-8'
关于参数ensure_ascii的解释:

    If ``ensure_ascii`` is true (the default), all non-ASCII characters in the output are escaped with ``\uXXXX`` sequences, and the result is a ``str`` instance consisting of ASCII characters only. If ``ensure_ascii`` is ``False``, some chunks written to ``fp`` may be ``unicode`` instances. This usually happens because the input contains unicode strings or the ``encoding`` parameter is used. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter``) this is likely to cause an error. 

关于参数encoding的解释:

``encoding`` is the character encoding for str instances, default is UTF-8. 

2.用python自带的json库将json转换成字典输出,输出是unicode码
在用json.loads(json_str)将json_str字符串转换成字典时,字典中的内容是unicode码,具体如下:

ud = json.loads(jd, encoding='utf-8')
print ud

输出结果:

{u'age': u'1', u'name': u'\u5f20\u4e09'} 

字典中的字符串都带的u,要想去掉u,有两种办法
a.使用yaml库的yaml.safe_load(jd)

import yaml
d = {'name': '张三', 'age': '1'} print d jd = json.dumps(d, ensure_ascii=False, encoding='utf-8')) ud = json.loads(jd, encoding='utf-8') print ud ud = yaml.safe_load(jd, encoding='utf-8') print ud 

结果输出为:

{u'age': u'1', u'name': u'\u5f20\u946b'} {'age': '1', 'name': u'\u5f20\u946b'} 

视觉明锐的同学可能发现第二个name的值前还是有u,也就是说他是unicode码。的确是的,上面的第1点已经说明了,直接打印字典,字典里面的中文就是乱码的,但是为什么是unicode码,需要更深一步分析,也希望知道的朋友不吝留言告知,谢谢。

b 递归实现转码函数自己去将json.loads()返回的字典从unicode码转成自己想要的码,实现如下:

def byteify(input, encoding='utf-8'): if isinstance(input, dict): return {byteify(key): byteify(value) for key, value in input.iteritems()} elif isinstance(input, list): return [byteify(element) for element in input] elif isinstance(input, unicode): return input.encode(encoding) else: return input 

使用示例:

d = {'name': '张三', 'age': '1'} print d jd = json.dumps(d, ensure_ascii=False, encoding='utf-8')) ud = json.loads(jd, encoding='utf-8') print ud ud = byteify(ud) print ud print ud['name'] 

输出结果如下:

{u'age': u'1', u'name': u'\u5f20\u946b'} {'age': '1', 'name': '\xe5\xbc\xa0\xe9\x91\xab'} 张三 

这次是彻底的将json.loads()返回的字典转换码成了utf-8,至于输出为什么是乱码?别忘了,开头第一点说的,直接print字典,中文是会乱码的,但是print ud['name'] 就会正常显示中文'张三'。
参考来源:https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json

 


作者:llicety
链接:https://www.jianshu.com/p/90ecc5987a18
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

转载于:https://www.cnblogs.com/uestc2007/p/10983970.html


http://www.niftyadmin.cn/n/4819753.html

相关文章

Windows Azure 架构指南 – 第 1卷 发布

公告:本博客为微软云计算中文博客的镜像博客。部分文章因为博客兼容性问题,会影响阅读体验。如遇此情况,请访问原博客。 正如 David Aiken 最近在其博客中提到的, Microsoft Patterns & Practices 团队发布了Windows Azure 架…

再谈动态创建网页元素收藏

再谈动态创建网页元素收藏 | 旧一篇: 代码重温&#xff1a;TZoCInetChecker——一个检测网络连接的类 <script>function StorePage(){ddocument;td.selection?(d.selection.type!None?d.selection.createRange().text:):(d.getSelection?d.getSelection():);void(keyi…

VC++6.0中使用OpenGL

来源:计算机世界:http://www2.ccw.com.cn/99/9934/9934b16.asp VC &#xff0b; &#xff0b; 6.0 中使 用OpenGL 清 华 大 学 李 勇 ----要 学 习OpenGL 编 程&#xff0c; 希 望 读 者 具 备 基 本 的 图 形 知 识。 本 文 使 用 基 于Visual C &#xff0b; &#xff0b; …

实验指令(3)

三层链路聚合&#xff1a; [SWB]interface Route-Aggregation 1 [SWB-Bridge-Aggregation1]exit [SWB]interface range G 1/0/21 to G 1/0/23 [SWB-if-range]port link-mode route [SWB-if-range]port link-aggregation group 1 [SWB-if-range]exit [SWB]interface route-Aggre…

vue tslint报错: Calls to 'console.log' are not allowed

使用Vue CLI 3 的 vue create 创建vuets 项目&#xff0c;使用默认配置&#xff0c; 控制台报警告Calls to console.log are not allowed&#xff0c;解决&#xff1a; 在tslint.json中的rules下 添加&#xff1a; "no-console": false。无需向在tsling.config中添加…

强制和别人QQ聊天代码

http://wpa.qq.com/msgrd?V1&Uin10001&Siteioshenmue&Menuyes http://wpa.qq.com/msgrd?V1&Uin*****&Siteioshenmue&Menuyes 收集自网络,请把*****处替换为你想要聊天的QQ号码,就像最上面的那个要和腾讯老总说话的10001一样.

如何编程动态改变IE的代理服务器设置, 并且使之马上生效!

如何编程动态改变IE的代理服务器设置, 并且使之马上生效! 选择自 sxxny 的 Blog 关键字 IE 代理服务器出处 最近有很多朋友都在讨论如何改变IE的代理服务器设置, 刚好我最近做的一个东西里面用到了这样的功能. 拿出来和大家共享一下. 用到的关键函数是wininet库里面的…

正则表达式学与练

这两天,开始学习正则表达式,并且开始练习了. 首先,我没有下载正则表达式测试器的程序,因为我使用的是一个网页测试器,它的代码来自于: 正则表达式练习器 http://www.codefans.com/ArticleView/Article_5600.html 打开上面的页面&#xff0c;把Html代码复制下来&#xff0c;保…