【发布时间】:2017-01-25 13:18:58
【问题描述】:
我的 python 脚本生成 json 文件。而且我必须支持这个在 windows 和 linux 上工作的 python 文件。问题是windows和linux上的不同回车。当我在 Windows 上运行此代码时,它会输出 CRLF json。当我在 linux 上运行它时,它会输出 LF json。
那么在python3.5中做json dump时如何显式设置回车呢?我可以
import json
fpath = "hoge.json"
data = {"AGE": 12, "HOGE": [{"GUA": 3}]}
with open(fpath, 'wt', encoding="utf-8") as outfile:
json.dump(data, outfile, indent=4, sort_keys=True, ensure_ascii=False)
【问题讨论】:
-
在创建文件后单独转换行尾可能更有意义。或者,更好的是,只使用行尾感知代码在另一端读取它;大多数读取 JSON 的软件应该能够处理以某种方式结束的不熟悉的行。
-
在 JSON 空白字符中,包括
\n和\r,在令牌之外被忽略,在令牌内部不允许(空格除外)。所以使用 Windows 或 UNIX 换行并没有什么不同。
标签: python json linux python-3.x carriage-return