我试图将字符串格式化为 JSON https://gist.github.com/jakub-g/b2ef123f8b754bc5c63bc854e7019987 using jq
我注意到 bash 与 zsh 的行为不同;特别是当 zsh 运行时jq
直接,结果与在子 shell 中运行时不同:\n
输入得到输出为\\n
在第一种情况下,与\n
在后者中。
我很困惑,不确定那里发生了什么:
- 这是已知的 zsh 行为吗?
- 这是一个
jq
bug?
- 或者它是否按设计工作,而我错过了一些东西?
BTW: 将换行符与 jq 一起使用 https://stackoverflow.com/questions/67391180/use-newline-with-jq建议使用printf %b
获得\n
代替\\n
,适用于 bash。但差异在于zsh
模式之间仍然存在。
$ jq --version
jq-1.6
# ---
# Using \n directly
bash-3.2$ jq --null-input --compact-output --raw-output --monochrome-output --arg test 'A\nB' '{test: $test}'
{"test":"A\\nB"}
bash-3.2$ OUT=$(jq --null-input --compact-output --raw-output --monochrome-output --arg test 'A\nB' '{test: $test}'); echo $OUT
{"test":"A\\nB"}
zsh-5.8.1> jq --null-input --compact-output --raw-output --monochrome-output --arg test 'A\nB' '{test: $test}'
{"test":"A\\nB"}
zsh-5.8.1> OUT=$(jq --null-input --compact-output --raw-output --monochrome-output --arg test 'A\nB' '{test: $test}'); echo $OUT
{"test":"A\nB"}
# -----
# Using `printf %b` to convert `\n` to real newline
bash-3.2$ jq --null-input --compact-output --raw-output --monochrome-output --arg test "$(printf %b 'A\nB')" '{test: $test}'
{"test":"A\nB"}
bash-3.2$ OUT=$(jq --null-input --compact-output --raw-output --monochrome-output --arg test "$(printf %b 'A\nB')" '{test: $test}'); echo $OUT
{"test":"A\nB"}
zsh-5.8.1> jq --null-input --compact-output --raw-output --monochrome-output --arg test "$(printf %b 'A\nB')" '{test: $test}'
{"test":"A\nB"}
zsh-5.8.1> OUT=$(jq --null-input --compact-output --raw-output --monochrome-output --arg test "$(printf %b 'A\nB')" '{test: $test}'); echo $OUT
{"test":"A
B"}
printf
两个 shell 之间的行为是相同的,所有与您的 shell 相关的 shell 扩展也是如此jq
调用——但默认echo
行为不同。
您可以通过切换来避免这种情况echo
to printf
.
% OUT=$(jq --null-input --compact-output --raw-output --monochrome-output --arg test "$(printf %b 'A\nB')" '{test: $test}')
% printf '%s\n' "$OUT"
{"test":"A\nB"}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)