为什么 jq 不过滤 'exp as $var | .'按记录打印原始输入?

问题描述 投票:0回答:1

jq 的文档 说(强调我的):

表达式

exp as $x | ...
表示:对于表达式
exp
的每个值,使用整个原始输入运行管道的其余部分,并将
$x
设置为该值。

这是我自己的解释:在

exp as $x | ...
中,
...
的上下文从
jq
命令的原始输入开始。如果是这样,为什么
exp as $x | .
不打印原始输入?这是我的示例(游乐场链接):

筛选:

(.signal[] | select(.name | contains("signal"))) as $matches | .

输入:

{
  "noise1": 5,
  "signal": [
    {
      "name": "child-signal-1",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-noise-2",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-signal-3",
      "nested": {
        "prop": "child-prop-3"
      }
    }
  ],
  "noise2": [
    {
      "name": "child-signal-1",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-noise-2",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-signal-3",
      "nested": {
        "prop": "child-prop-3"
      }
    }
  ]
}

输出:

{
  "noise1": 5,
  "signal": [
    {
      "name": "child-signal-1",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-noise-2",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-signal-3",
      "nested": {
        "prop": "child-prop-3"
      }
    }
  ],
  "noise2": [
    {
      "name": "child-signal-1",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-noise-2",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-signal-3",
      "nested": {
        "prop": "child-prop-3"
      }
    }
  ]
}
{
  "noise1": 5,
  "signal": [
    {
      "name": "child-signal-1",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-noise-2",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-signal-3",
      "nested": {
        "prop": "child-prop-3"
      }
    }
  ],
  "noise2": [
    {
      "name": "child-signal-1",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-noise-2",
      "nested": {
        "prop": "child-prop-3"
      }
    },
    {
      "name": "child-signal-3",
      "nested": {
        "prop": "child-prop-3"
      }
    }
  ]
}

我还想了解为什么我的输出将输入打印两次,从而使其无效 json。我认为这与

(.signal[] | select(.name | contains("signal")))
返回 2 个结果有关,但我不明白如果我没有引用 RHS 上的变量,这有什么关系。

json bash command-line-interface jq
1个回答
0
投票

更简单的例子:

jq -c '.[] as $x | .' <<<'[ "abc", "def" ]'
["abc","def"]
["abc","def"]

.
is 整个输入,如文档所示。

但是表达式会被计算多次。这源于使用

[]

如果使用

.[index]
语法,但完全省略索引,它将返回数组元素的 all。使用输入
.[]
运行
[1,2,3]
会将数字生成为三个单独的结果,而不是单个数组。
.foo[]
形式的过滤器相当于
.foo | .[]

我们可以看到这个:

jq -c '.[] as $x | [ ., $x ]' <<<'[ "abc", "def" ]'
[["abc","def"],"abc"]
[["abc","def"],"def"]
© www.soinside.com 2019 - 2024. All rights reserved.