Python 在json列表中的文件中写入json
我多次调用一个API以获得结果。结果以json格式返回。我正在将所有结果保存在一个列表中。收到所有数据后,我使用以下代码将列表内容写入文件。我的最终目标是用有效的json将结果保存在一个文件中。但是,下面的代码将Python 在json列表中的文件中写入json,python,json,parsing,Python,Json,Parsing,我多次调用一个API以获得结果。结果以json格式返回。我正在将所有结果保存在一个列表中。收到所有数据后,我使用以下代码将列表内容写入文件。我的最终目标是用有效的json将结果保存在一个文件中。但是,下面的代码将'\'添加到json结果文件中。有人能帮我解决这个问题吗 result = [] // In a for loop I append json results to this list. I have not written the code here. // Then I use th
'\'
添加到json结果文件中。有人能帮我解决这个问题吗
result = []
// In a for loop I append json results to this list. I have not written the code here.
// Then I use this code to write to a file.
with open(host_log_path, 'w') as log_file:
log_file.write(json.dumps(result))
带斜杠的电流输出示例:
["{\"hdr\":{\"msgt\":\"InitialState\",\"ver\":\"CV-NOTSET\",\"uid\":1,\"seq\":1}}"]
您得到的输出表明
result
包含JSON字符串列表,而不是对象列表。您不需要调用json.dumps()
,它们已经格式化为json。您应该在日志文件中将它们作为单独的一行写入
with open(host_log_path, "a") as log_file:
for msg in result:
log_file.write((msg if type(msg) is str else json.dumps(msg)) + "\n")
您还应该使用a
模式附加到日志文件。每次打开代码时,它都会清除旧内容
如果要将它们编写为单个JSON数组,可以在循环中调用JSON.loads()
with open(host_log_path, "w") as log_file:
msgs = [json.loads(msg) if type(msg) is str else msg for msg in result]
json.dump(msgs, log_file)
这意味着
result
已经是JSON,您不需要调用JSON.dumps()
。实际上,它似乎是一个包含JSON字符串的列表。该列表包含多个带有JSON字符串的记录。这解决了slashe的问题,但如何使同一对象的所有项都成为类似于数组中的内容。[]如果您想这样做,您需要使用json.loads()
来解析json,将它们全部收集到一个列表中,然后将其转储。您能给出一个代码示例吗?因为当我尝试json.loads()时,它不起作用。可能是我遗漏了一些非常简单的东西。我在答案中添加了这一点。json.lods()行给出了这个错误。返回_default_decoder.decode(s)文件“/usr/lib/python2.7/json/decoder.py”,第364行,在decode obj中,end=self.raw_decode(s,idx=_w(s,0.end())文件“/usr/lib/python2.7/json/decoder.py”,第382行,在raw_decode raise ValueError中(“无法解码任何json对象”)ValueError:无法解码任何json对象