我多次调用一个 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 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
mode 附加到日志文件。每次您打开它时,您的代码都会清除旧内容。
如果要将它们编写为单个 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句