JQ JSON select 带有动态 shell 参数

JQ JSON select with dynamic shell param

我使用 JQ JSON 格式化和过滤数据。

sed "s/.*Service - //p" tes.log | jq 'if (.requests | length) != 0 then .requests |= map(select(.orderId == "2260")) else "NO"  end' > ~/result.log

这里orderid硬编码为2260,但我的要求是参数驱动

所以我将参数存储到一个名为 ORDER_ID 的变量中,例如,

ORDER_ID=2260

然后使用 $ORDER_ID,但它不起作用。

sed "s/.*Service - //p" tes.log | jq 'if (.requests | length) != 0 then .requests |= map(select(.orderId == "$ORDER_ID")) else "NO"  end' > ~/result.log

它不会用传递的参数替换 $ORDER_ID。

谢谢

shell不展开单引号内的变量。如果 jq 不知道引号类型,请尝试在整个过程中交换双引号和单引号。此外,如果您只想 select 包含 Service - 的行,则需要 sed 的 -n 标志:

sed -n 's/.*Service - //p' tes.log | jq "if (.requests | length) != 0 then .requests |= map(select(.orderId == '$ORDER_ID')) else 'NO' end" > ~/result.log

如以下 bash 脚本所示,Stephen Gildea 的示例将不起作用,因为 jq 不允许使用 ' 单引号。

#!/bin/bash
ORDER_ID=2260

jq "if (.requests | length) != 0 then .requests |= map(select(.orderId == '$ORDER_ID')) else 'NO' end" <<EOF
{"requests":[{"orderId":2260}]}
EOF

特别是 'NO' 文字会产生语法错误:

jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at <top-level>, line 1:
if (.requests | length) != 0 then .requests |= map(select(.orderId == '2260')) else 'NO' end                                                                      
jq: error: Possibly unterminated 'if' statement at <top-level>, line 1:
if (.requests | length) != 0 then .requests |= map(select(.orderId == '2260')) else 'NO' end
jq: 2 compile errors

一种可行的方法是使用 --argjson 选项,对整个 jq 过滤器使用单引号,对过滤器内的字符串文字使用双引号。例如

jq --argjson ORDER_ID "$ORDER_ID" '
if (.requests|length)!=0 then .requests |= map(select(.orderId == $ORDER_ID)) else "NO" end
'