【发布时间】:2015-08-11 09:40:21
【问题描述】:
我有一个 Django 应用,使用 tasypie 序列化一些数据。
有个名字
"Glòria"
(带有重音符号'o')在数据库中,但这没有被正确序列化。在tasypie生成的json中,输出为
"Glòria"
序列化程序类如下所示:
import json as simplejson
class PrettyJSONSerializer(Serializer):
json_indent = 2
def to_json(self, data, options=None):
options = options or {}
data = self.to_simple(data, options)
return simplejson.dumps(data, cls=json.DjangoJSONEncoder,
sort_keys=True, ensure_ascii=False, indent=self.json_indent)
将 simplejson.dumps 上的属性更改为
ensure_ascii=True
返回以下内容:
"Gl\u00f2ria"
【问题讨论】:
-
这是 Python 2 还是 3?如果是 Python 2,名称是由
str还是unicode对象表示的? -
Python 2.7,内部存储为unicode,调试器显示:u'Gl\xf2ria'
-
"Gl\u00f2ria"版本实际上是Glòria的有效 JSON 表示。您确定ensure_ascii=False的问题在于序列化程序而不是客户端吗? -
我没有看到“Gl\u00f2ria”的问题,但它不是我想要返回的。我想设置 ensure_ascii=False,并让它输出一个 ò'' 而不是 'ò'
-
嗯。我不知道 Django 或 sweetpie,所以可能有一种正确的方法来解决这个问题,但是 FWIW,您可以轻松地将 Unicode 转义转换为正确的 Unicode。例如,
s="this is a Gl\u00f2ria test".decode('unicode-escape');print s,repr(s)打印this is a Glòria test u'this is a Gl\xf2ria test'。至少,如果您的控制台设置为使用 utf-8 编码,它会打印出来。 :)
标签: python django serialization unicode tastypie