使用 JQ 和 bash 处理包含新行的 JSON

Jon*_*ger 5 bash echo jq

我收到一个带有 curl 调用的 JSON,类似于以下内容:

output="$(curl -s "$api_url")"
Run Code Online (Sandbox Code Playgroud)

此输出为 JSON 格式,必须由 jq 处理,如下所示:

{
    "test": "Hello\nThere!"
}
Run Code Online (Sandbox Code Playgroud)

现在,我正在使用以下echo管道组合来使 jq 工作:

test="$(echo "$output" | jq -r ".test")"
Run Code Online (Sandbox Code Playgroud)

但是,这不适用于示例输入,因为它在 JSON 和 JQ 错误中包含新行 parse error: Invalid string: control characters from U+0000 through U+001F must be escaped at line 2, column 6

有什么办法可以改变数据,让 jq 可以理解吗?

l0b*_*0b0 8

所以文字输入是这样的:

$ output='{
>     "test": "Hello
> There!"
> }'
$ echo "$output" | jq -r ".test"
parse error: Invalid string: control characters from U+0000 through U+001F must be escaped at line 3, column 7
Run Code Online (Sandbox Code Playgroud)

JSON没有多行字符串。因此,如果您从 API 获取此文字值,则这是一个API 错误,应该在服务器端修复。


既然你说 API 实际上返回类似的东西{"test": "Hello\nThere!"},那么问题一定出在你的命令上,因为这适用于 Bash 4.4.23 中的 jq 1.5:

$ output='{"test": "Hello\nThere!"}'
$ echo "$output" | jq -r ".test"
Hello
There!
Run Code Online (Sandbox Code Playgroud)

eval(这是邪恶的),echo -e其他特殊命令可能会导致转义字符被解码。尝试使用printf '%s' "$output"替代。调试此问题需要有关您的环境的更多信息。

  • 在 `bash` 中,根据 `echo '\n'` 输出 `\n<newline>` 还是 `<newline><newline>` 取决于 bash 的构建方式以及环境/选项(`posix` 和 `xpg_echo ` 至少在这里)。更一般地说,不能使用“echo”输出任意数据。 (2认同)