如何使用 python -m json.tool 包含 \n

How to include \n with python -m json.tool

我正在尝试通过 shell 创建一个 json 文件,但是,现在允许换行并且出现错误。

Invalid control character at: line 5 column 26 (char 87) 指向 \n

echo '{
    "param1": "asdfasf",
    "param2": "asffad",
    "param3": "asdfsaf",
    "param4": "asdfasf\nasfasfas"
}' | python -m json.tool > test.json

假设我想保留新行,我怎样才能将其放入 json 文件?

更新:

我认为这与 python 的 json encoder/decoder 的严格模式有关。

If strict is False (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0-31 range, including '\t' (tab), '\n', '\r' and '[=17=]'.

https://docs.python.org/2/library/json.html

如何从 python -m json.tool 中将严格模式设置为 False

转义 \ 似乎可以解决问题:

echo  '{
    "param1": "asdfasf",
    "param2": "asffad",
    "param3": "asdfsaf",
    "param4": "asdfasf\nasfasfas"
}' | python -m json.tool > test.json

它创建有效的 json:

with open('/home/test.json', 'rU') as f:
    js = json.load(f)
    print(js)
    print(js["param4"])

输出:

{'param1': 'asdfasf', 'param3': 'asdfsaf', 'param2': 'asffad', 'param4': 'asdfasf\nasfasfas'}
asdfasf
asfasfas

zsh 正在用适当的回车 return 替换 \n。您可以转义它或改用 heredoc 样式:

python -m json.tool > test.json << EOF
{
"param1": "asdfasf",
"param2": "asffad",
"param3": "asdfsaf",
"param4": "asdfasf\nasfasfas"
}
EOF