Python中的JSON转储:在文件中编写换行符和回车。

9

当我使用以下命令打开并将有效的JSON写入文件时,它会在数据中写入换行符和回车符。

with open('logs/output.json', 'w') as outfile:
     json.dump(json_data, outfile, indent=2, separators=(',', ': '))

output.json的格式大致如下:

{\r\n \"config\": {\r\n \"app\": {\r\n \"calendar\": {\r\n \"{tenant-key}calendar.reference }

我该如何防止这种情况发生?

我之前在将 JSON 字符串转换为 JSON 时也遇到过类似的情况。json_data 的类型是什么? - Keith John Hutchison
1
你到底如何防止 什么?预期输出会是什么? - Martijn Pieters
2
回车符根据JSON规范是有效的。为什么您想禁用这个默认且通常有效的行为呢? - Rich Tier
2个回答

5
json.dump(json_data, outfile, separators=(',', ':'))

只有当您希望在新行上缩进时,才需要缩进关键字参数。这样做会激活“漂亮的打印”。


2

我通过类似以下的方式使得某些功能可用:

最初的回答:

newJson = json.dump(json_data, outfile, indent=2, separators=(',', ': '))
with open('logs/output.json', 'w') as json_file:
        json_file.write(newJson)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接