json.loads()返回一个unicode对象而不是字典

Dr *_*ato 13 python unicode json fabric python-2.7

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

from StringIO import StringIO

output = StringIO()
get(file_name, output)

output = output.getvalue()
Run Code Online (Sandbox Code Playgroud)

现在的价值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))

有没有办法解决这个问题呢?

干杯

m.w*_*ski 18

您的数据已转义.

json.loads(output.decode('string-escape').strip('"'))
Run Code Online (Sandbox Code Playgroud)

应该给你想要的结果:

Out[12]: {'reason': 'Record already exists.', 'status': 'failed'}
Run Code Online (Sandbox Code Playgroud)

  • 注意,只有当`output`是JSON字符串的Python字节字符串编码时才会正常工作,而不是如果它是双JSON.两种字符串格式之间存在差异 - 尽管从上面的示例数据中看不到它们,因此无法确定哪种方法是正确的.我怀疑双JSON比JSON-in-Pybytestring更可能. (2认同)

And*_*ark 14

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