【发布时间】:2019-01-10 09:04:18
【问题描述】:
我正在尝试返回一个带有特殊字符的 json 对象。 崩溃的行是:
return json.dumps([x.toDict() for x in searches], ensure_ascii=False)
toDict 函数:
def toDict(self):
"""Expect to dico. Needed before serialization in JSON"""
out = {}
if self.wkid is not None:
out['wkid'] = self.wkid
if self.wkt is not None:
out['wkt'] = self.wkt
return(out)
当我在for x in searches 中打印 x 时:
for x in searches:
print x.toDict()
{'crs': {'wkid': 4326, 'wkt': 'WGS84'}, 'candidates': [{'score': 200, 'type': 'ADR', 'location': {'y': 50.2485465358886, 'x': 4.38243469412172, 'crs': {'wkid': 4326, 'wkt': 'WGS84'}}, 'address': {'city': 'Fontenelle', 'munkey': '0585'}}, {'score': 200, 'type': 'ADR', 'location': {'y': 50.4123146893214, 'x': 4.32436581556278, 'crs': {'wkid': 4326, 'wkt': 'WGS84'}}, 'address': {'city': "Fontaine-l'\\xe3\\x89v\\xe3\\xaaque", 'munkey': '0324'}}, {'score': 200, 'type': 'ADR', 'location': {'y': 50.3217667573625, 'x': 4.21386030471998, 'crs': {'wkid': 4326, 'wkt': 'WGS84'}}, 'address': {'city': 'Fontaine-valmont', 'munkey': '0362'}}, {'score': 200, 'type': 'ADR', 'location': {'y': 49.7151404477129, 'x': 5.23438436377951, 'crs': {'wkid': 4326, 'wkt': 'WGS84'}}, 'address': {'city': 'Fontenoille', 'munkey': '0541'}}], 'id': u'1', 'address': {'city': u'Fontaine-lev', 'street': u'Avenue des Chones', 'zone': u'1301', 'house': u'19'}}
这很好用。但是,当我尝试时:
for x in searches:
print json.dumps(x.toDict(), ensure_ascii=False)
我得到的错误是:
UnicodeDecodeError('ascii', '"Fontaine-l\\'\\xe3\\x89v\\xe3\\xaaque"', 12, 13, 'ordinal not in range(128)')
'ascii' codec can't decode byte 0xe3 in position 12: ordinal not in range(128).
奇怪,考虑到我通过 ensure_ascii=False 来指定文本不应该被解码..
它仍在尝试解码文本可能有什么问题?
【问题讨论】:
-
这个字符串是从 PostGreSQL 数据库中获取的。我已经编辑了我的 OP 以包含完整的对象,按原样打印它可以正常工作,但是使用 json.dumps(object, ensure_ascii=False) 仍然会因 unicode 错误而崩溃。我会调查错误的编码,但我仍然有点困惑,为什么即使指定它应该在不解码的情况下按原样返回它也会崩溃..
标签: python json ascii non-ascii-characters