如何使用 jq select JSON 中位于两个不同层(数组和字符串)中的两个键?
How to select two keys from JSON that are located in two different layers (array and a string) using jq?
我有一个 bash 脚本,我需要在其中解析某些数据以使其根据检索到的数据做出正确反应。
数据可以导出为JSON,所以这就是我正在做的。
我想知道我是否可以用 JQ 解析这个 JSON 以一次性获取我需要的数据。
结构如下:
[{"long_message":
{
"just":"a",
"bunch":"of",
"unrelated":"data",
"can be":"omitted"
},
"status": {
"message":"CRITICAL",
"code":1
},
"service":"SERVICE_NAME",
"message":"you messed up"
}]
我需要获取 'code' 和第二个 'message' 的值。可能吗?
我无法根据jq的文档弄明白,所以也许比我更了解它的人可以提供帮助。
我当前的代码是:
jq -r '.[].status.code && .[].message'
...它失败了:
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
提前致谢。
P.S.: 有没有办法将数据放入 shell 变量?
来自 jq 的 NUL 分隔输出允许您将其读入 bash 变量,即使它包含换行符或其他分隔符(我们可能会看到 - 考虑 "message": "first line\nsecond line"
)。
您可以使用 jq -j
(类似于 -r
,但没有自动换行),然后使用 "\u0000"
添加显式 NUL。在bash这边,阅读需要的练习在BashFAQ #001中给出——在其中搜索NUL
。
放在一起,看起来像:
#!/usr/bin/env bash
while IFS= read -r -d '' code && IFS= read -r -d '' message; do
echo "Got code: <$code> and message: <$message>"
done < <(jq -j '.[] | (.status.code, "\u0000", .message, "\u0000")' <input.json)
我有一个 bash 脚本,我需要在其中解析某些数据以使其根据检索到的数据做出正确反应。 数据可以导出为JSON,所以这就是我正在做的。
我想知道我是否可以用 JQ 解析这个 JSON 以一次性获取我需要的数据。
结构如下:
[{"long_message":
{
"just":"a",
"bunch":"of",
"unrelated":"data",
"can be":"omitted"
},
"status": {
"message":"CRITICAL",
"code":1
},
"service":"SERVICE_NAME",
"message":"you messed up"
}]
我需要获取 'code' 和第二个 'message' 的值。可能吗? 我无法根据jq的文档弄明白,所以也许比我更了解它的人可以提供帮助。
我当前的代码是:
jq -r '.[].status.code && .[].message'
...它失败了:
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
提前致谢。
P.S.: 有没有办法将数据放入 shell 变量?
来自 jq 的 NUL 分隔输出允许您将其读入 bash 变量,即使它包含换行符或其他分隔符(我们可能会看到 - 考虑 "message": "first line\nsecond line"
)。
您可以使用 jq -j
(类似于 -r
,但没有自动换行),然后使用 "\u0000"
添加显式 NUL。在bash这边,阅读需要的练习在BashFAQ #001中给出——在其中搜索NUL
。
放在一起,看起来像:
#!/usr/bin/env bash
while IFS= read -r -d '' code && IFS= read -r -d '' message; do
echo "Got code: <$code> and message: <$message>"
done < <(jq -j '.[] | (.status.code, "\u0000", .message, "\u0000")' <input.json)