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

标签 python json shell python-2.7 zsh

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

控制字符无效:第 5 行第 26 列(字符 87) 指向 \n

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

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

更新:

我认为这与 python 的 json 编码器/解码器的严格模式有关。

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 '\0'.

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

关于python - 如何使用 python -m json.tool 包含\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31944872/

相关文章:

python - 如何使用可变补丁大小的 tf.random_crop 定义形状?

c# - Azure Function 返回多个 JSON 对象

javascript - 在 JSobject 中追加元素

linux - RH Linux Bash 脚本帮助。需要移动文件中含有特定单词的文件

node.js - 将 KillAll 发送到多 Node 进程并等待响应

mysql - Shell 脚本 - 下载文件 - Mysql 替换

python - Pandas :删除非整数数据

python - 如何按时执行脚本?

python - 如何在 Python 中按句子拆分段落

ios - AFNetworking-iOS在PHP打印时获取JSON