JQ JSON选择动态shell参数

时间:2015-04-28 18:07:51

标签: json shell jq

我使用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.但我的要求是让它参数驱动。

所以我将param存储到一个名为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

它没有用传递的param替换$ ORDER_ID。

由于

2 个答案:

答案 0 :(得分:1)

shell不会在单引号内扩展变量。如果jq与引用类型无关,请尝试在整个过程中交换双引号和单引号。另外,如果您只想选择其中包含Service -的行,则需要{\ n} -n标记为sed:

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

答案 1 :(得分:0)

正如以下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过滤器使用单引号,对过滤器中的字符串文字使用双引号。 E.g。

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