[英]json.loads() is returning a unicode object instead of a dictionary
我正在使用Fabric從遠程服務器上的文件中讀取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.loads(output.decode('string-escape').strip('"'))
應該給您想要的結果:
Out[12]: {'reason': 'Record already exists.', 'status': 'failed'}
解決方案是首先弄清楚為什么對文件進行雙JSON編碼,但是鑒於數據兩次通過json.loads
傳遞是正確的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.