jq:错误:无法减去数字和对象

时间:2016-10-19 11:25:51

标签: jq

我正在使用jq 1.4并且对以下情况感到困惑。我可以计算一个数字,但是当我尝试用这个数字构造一个对象时会出错:

echo '{"aggregations":{"sent":{"value":25},"bounced":{"value":null},"incoming_act":{"value":25}}}' |
  jq '.aggregations
      | {"num_sent": .sent.value, "num_incoming_act": .incoming_act.value }
      | .num_sent as $x
      | .num_incoming_act as $y
      | $y-$x as $d
      | $d'
0

工作正常。但

echo '{"aggregations":{"sent":{"value":25},"bounced":{"value":null},"incoming_act":{"value":25}}}' |
  jq '.aggregations
      | {"num_sent": .sent.value, "num_incoming_act": .incoming_act.value }
      | .num_sent as $x
      | .num_incoming_act as $y
      | $y-$x as $d
      | {diff: $d}'
jq: error: number and object cannot be subtracted

不起作用。当我在最后一部分要求对象时也会发生同样的情况:

echo '{"aggregations":{"sent":{"value":25},"bounced":{"value":null},"incoming_act":{"value":25}}}' |
  jq '.aggregations
      | {"num_sent": .sent.value, "num_incoming_act": .incoming_act.value }
      | .num_sent as $x
      | .num_incoming_act as $y
      | $y-$x as $d 
      | objects'
jq: error: number and object cannot be subtracted

我喜欢jq的管道系统。但是,这里似乎正在发生一些事情。我在第一个例子中得到的“0”是多少?它似乎不是正常的数字0.这再次起作用:

jq -n ' 0 as $x | {diff: $x} '

2 个答案:

答案 0 :(得分:1)

在出现错误的示例中,请写下($y-$x) as $d而不是$y-$x as $d。在撰写(COMPOUND INFIX EXPRESSION) as $variable时,括号有时是必要的,并且始终是可取的。

说明:

解析器处理表单的表达式:

3-2 as $d | EXPR

为:

3-(2 as $d | EXPR)

这意味着3-2 as $d|$d被解析为3-(2 as $d|$d),其评估为3-2。但请注意,在这种情况下,$ d本身的值为2.

答案 1 :(得分:0)

echo '{"aggregations":{"sent":{"value":25},"bounced":{"value":null},"incoming_act":{"value":12}}}' | jq '.aggregations | {"num_sent": .sent.value, "num_incoming_act": .incoming_act.value } | {diff:(.num_sent as $x | .num_incoming_act as $y | $y-$x as $d | $d)}'

将产生:

{
  "diff": -13
}

差异就在这里;

上一篇:.num_sent as $x | .num_incoming_act as $y | $y-$x as $d | {diff: $d}'

现在:{diff:(.num_sent as $x | .num_incoming_act as $y | $y-$x as $d | $d)}'

您可以通过可视化显示差异来看到,jq处理事物的位置。