使用json.dumps时出现UnicodeDecodeError

时间:2018-08-02 14:33:26

标签: python json ascii non-ascii-characters

我正在尝试返回带有特殊字符的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).

奇怪,考虑到我传递了sure_ascii = False来指定不应解码文本。

它仍在尝试解码文本,这可能是什么问题?

1 个答案:

答案 0 :(得分:2)

ensure_ascii=False并不意味着它不会解码unicode文字。

  

如果sure_ascii为false,则写入fp的某些块可能是unicode实例。通常会发生这种情况,因为输入包含unicode字符串或使用了encoding参数。 除非fp.write()明确理解unicode(如codecs.getwriter()一样),否则很可能会导致错误。

来自python doc