【问题标题】:json serialization outputting accented character incorrectly, python / djangojson序列化错误地输出重音字符,python / django
【发布时间】: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


【解决方案1】:

我不能发表评论(还......)所以我发布了回复。 Python 2 的编码并不是很有趣。

Glòria 是以字节为单位的数据的正确 utf-8 编码表示。 Gl\u00f2ria 是 unicode 字符串的 Python 2 内部表示。 json.dumps 返回一个 python unicode 字符串。您可能想要做的是将 json.dumps 的输出编码为 utf8。

import json
data = u'Gl\xf2ria'
encoded_data = json.dumps(s, ensure_ascii=False).encode("utf8")
print(encoded_data)

打印 Glòria。

编辑:只是为了确保

Glòria = Gl\xc3\xb2ria。使用 print 语句打印时,两者都应正确显示为 Glòria。

【讨论】:

  • 你是对的,它可能是基于网络浏览器的问题,因为在命令行上使用 curl 可以正确显示它。
  • 也许你对这件事很熟悉,但万一以后有人读到这里不熟悉:有必要定义内容编码。 text/html 为此提供了 html 标签,但 application/json 之类的东西可能需要将编码添加到 Content-type HTTP 标头才能在浏览器上正确显示(Content-type: application/json; charset=utf-8 i>)。
猜你喜欢
  • 2011-07-05
  • 2014-07-24
  • 2015-02-07
  • 2018-07-05
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
相关资源
最近更新 更多