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

标签 python json python-2.7 unicode fabric

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

from StringIO import StringIO

output = StringIO()
get(file_name, output)

output = output.getvalue()

output 的值现在是:

'"{\\n\\"status\\":\\"failed\\",\\n\\"reason\\":\\"Record already 存在。\\"\\n}"'

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

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

json.loads(json.loads(输出))

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

干杯

最佳答案

您的数据已转义。

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

应该给你想要的结果:

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

关于python - json.loads() 返回一个 unicode 对象而不是一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22600128/

相关文章:

python - ` d3 = {**d1, **d2}` 和 `d4 = dict(**d1, **d2)` 之间的区别?

python - 计算 tensorflow 中每个维度的元素数量

python - 将具有形状 (M, N, P) 数组的 numpy int 数组高效转换为具有 (N, P) 形状的二维对象数组

javascript - JSON 加载函数从其他程序读取 key

Python 帮助 |从底部读取文本文件中的数据

python - 重新排列 numpy 数组中的子数组?

python - 修改json文件

javascript - .json() 函数在 Angular2 中有什么作用?

python - 如何? : Setting up Bokeh w/Redis Backend

python-2.7 - scrapy 网络爬虫教程中的错误