Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何去掉json文件中的所有“\”_Python_Json - Fatal编程技术网

Python 如何去掉json文件中的所有“\”

Python 如何去掉json文件中的所有“\”,python,json,Python,Json,我在python中工作,我有一个json文件,如下所示: "{\"label\": \"red\", \"seconds\": 20}" "{\"label\": \"blue\", \"seconds\": 10}" {label: red, seconds: 20} {label: blue, seconds: 10} 我想去掉

我在python中工作,我有一个json文件,如下所示:

"{\"label\": \"red\", \"seconds\": 20}"
"{\"label\": \"blue\", \"seconds\": 10}"
{label: red, seconds: 20}
 {label: blue, seconds: 10}
我想去掉所有的反斜杠和引号,如下所示:

"{\"label\": \"red\", \"seconds\": 20}"
"{\"label\": \"blue\", \"seconds\": 10}"
{label: red, seconds: 20}
 {label: blue, seconds: 10}
我附上了代码,以展示如何获得json文件,该文件由一个单独的json对象字符串组成

for value in finalOutputList:
    newOutputString = json.dumps(value)
    finalOutputString += (newOutputString + "\n")

with open('data.json', 'a') as outfile:
    for item in outputString.splitlines():
        json.dump(item, outfile)
        outfile.write("\n")

问题:您正在对对象进行双重编码,例如:

对于FinalOutList中的值: newOutputString=json.dumpsvalue在这里用json.dumps编码 finalOutputString+=newOutputString+\n 打开'data.json','a'作为输出文件: 对于outputString.splitlines中的项: json.dumpitem,outfile。不必要地再次编码 outfile.write\n 解决方案:删除双重编码,只编码一次,例如:

对于FinalOutList中的值: newOutputString=json.dumpsvalue保留此编码 finalOutputString+=newOutputString+\n 打开'data.json','a'作为输出文件: 对于outputString.splitlines中的项: outfile.writeitem更改为只在此处写入已编码的json字符串 outfile.write\n
您可以将其切换为另一种方式,这样在写入文件时可以使用json.dumps,然后只保留finalOutputString,但我建议您使用刚才演示的方式。

您必须使用json.loads。这是否回答了您的问题?我有一个json文件,看起来像这样…这不是有效的json-你错过了一些吗?它只是两个彼此没有连接的字符串。它不能作为JSON进行解码。不管怎样,它看起来好像在某个点上被双重编码了。因此,解决这个问题的办法是更正使其成为那样的代码,而不是一开始就以那种格式存储它。我在您的代码中看到您两次使用json.dump,这很可能是问题的原因。@Supercol我在您之前的帖子中警告过您对象被双重编码,我会给您写一个答案,修复这个问题中写入文件的方式。@Supercol我已经给出了答案。对你有用吗?