【问题标题】:UnicodeDecodeError when using json.dumps使用 json.dumps 时出现 UnicodeDecodeError
【发布时间】: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


【解决方案1】:

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

如果 ensure_ascii 为 false,则写入 fp 的某些块可能是 unicode 实例。这通常是因为输入包含 unicode 字符串或使用了编码参数。 除非 fp.write() 明确理解 unicode(如在 codecs.getwriter() 中),否则这可能会导致错误。

来自python doc

【讨论】:

  • 谢谢,我不知道。我得看看这个字符串是如何在数据库中编码的,以及我应该如何正确解码它。
猜你喜欢
  • 2013-11-21
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多