【问题标题】:json.loads() is returning a unicode object instead of a dictionaryjson.loads() 返回一个 unicode 对象而不是字典
【发布时间】:2014-05-01 06:17:41
【问题描述】:

我正在使用结构从远程服务器上的文件中读取 json:

from StringIO import StringIO

output = StringIO()
get(file_name, output)

output = output.getvalue()

output 的值现在是:

'"{\\n \\"status\\": \\"failed\\", \\n \\"reason\\": \\"Record already exists.\\"\\n}"'

当我尝试使用 json.loads(output) 将此字符串解析为字典时,它会返回 unicode 对象 u'{\n "status": "failed", \n "reason": "Record already exists."\n}' 而不是字典。

我想出了一个相当糟糕的解决方法,只是将新的 unicode 对象传回 json.loads():

json.loads(json.loads(output))

有没有其他办法解决这个问题?

干杯

【问题讨论】:

  • 如果给定的数据是一串json字符串,那么这个方法有什么问题呢?我认为json.loads(json.loads(..)) 是一个很好的解决方案。你是不是有点太担心了?

标签: python json python-2.7 unicode fabric


【解决方案1】:

这里的解决方案是首先弄清楚为什么您的文件被双重 JSON 编码,但考虑到数据通过 json.loads 两次是正确的方法。

【讨论】:

  • 太好了,在我的情况下,我首先使用 json.dumps(my_data) 将 json 数据插入到 MariaDB 中,然后在 INSERT 查询中使用 MariaDB 的 JSON_QUOTE 方法,这有点像 json.dumps .因此,它对其进行了两次编码。您的回答帮助我走上了正轨。
【解决方案2】:

你的数据被转义了。

json.loads(output.decode('string-escape').strip('"'))

应该会给你想要的结果:

Out[12]: {'reason': 'Record already exists.', 'status': 'failed'}

【讨论】:

  • 请注意,这只有在 output 是 JSON 字符串的 Python 字节字符串编码时才能正常工作,如果它是双 JSON 则不能。两种字符串格式之间存在差异——尽管从上面的示例数据中看不到它们,因此无法确定哪种方法是正确的。我怀疑双 JSON 比 JSON-in-Pybytestring 更有可能。
猜你喜欢
  • 1970-01-01
  • 2016-09-07
  • 2019-05-04
  • 2020-02-15
  • 1970-01-01
  • 2023-03-18
  • 2015-08-15
  • 2013-12-29
  • 2019-11-06
相关资源
最近更新 更多