Python编码和JSON转储 [英] Python encoding and json dumps

查看:48
本文介绍了Python编码和JSON转储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,这个问题是您早些时候提出的.我仍然不清楚在python3.2中编码.

I apologize if this question has been asked earlier. I am still not clear about encoding in python3.2.

我正在读取一个csv(以UTF-8编码(不带BOM)),并且在csv中有法语口音.

I am reading a csv(encoded in UTF-8 w/o BOM) and I have French accents in the csv.

以下是打开和读取csv文件的代码:

Here is the code to opening and reading the csv file:

csvfile = open(in_file, 'r', encoding='utf-8')
fieldnames = ("id","locale","message")    
reader = csv.DictReader(csvfile,fieldnames,escapechar="\\") 
for row in reader:
        if row['id'] == id and row['locale'] == locale:
            out = row['message'];

我将以Json的身份返回邮件(出)

I am returning the message(out) as Json

jsonout = json.dumps(out, ensure_ascii=True)    
return HttpResponse(jsonout,content_type="application/json; encoding=utf-8")

但是,当我预览结果时,口音e(法语)被\ u00e9替换.

However when I preview the result I get the accent e(French) being replaced by \u00e9 .

请问我做错了什么以及应该怎么做,以便json输出以重音显示正确的e.

Can you please advice on what I am doing wrong and what should I do so that the json output shows the proper e with accent.

谢谢

推荐答案

您没有做错任何事(Python也不是).

You're doing nothing wrong (and neither is Python).

Python的json模块仅采用安全路由并转义非ASCII字符.这是在json中表示此类字符的有效方法,任何符合条件的解析器在解析字符串时都将恢复正确的Unicode字符:

Python's json module simply takes the safe route and escapes non-ascii characters. This is a valid way of representing such characters in json, and any conforming parser will resurrect the proper Unicode characters when parsing the string:

>>> import json
>>> json.dumps({'Crêpes': 5})
'{"Cr\\u00eapes": 5}'
>>> json.loads('{"Cr\\u00eapes": 5}')
{'Crêpes': 5}

别忘了json只是数据的表示形式,ê" "\\ u00ea" 都是字符串ê.符合条件的json解析器应该正确处理这两者.

Don't forget that json is just a representation of your data, and both "ê" and "\\u00ea" are valid json representations of the string ê. Conforming json parsers should handle both correctly.

但是可以禁用此行为,请参见 json.dump 文档:

It is possible to disable this behaviour though, see the json.dump documentation:

>>> json.dumps({'Crêpes': 5}, ensure_ascii=False)
'{"Crêpes": 5}'

这篇关于Python编码和JSON转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆