jq具有来自不同来源的多个输入

问题描述:

使用jq时如何混合不同的输入源? 对于特定的用例,我想将文件中的一些数据添加到标准输出中通过管道传输的Feed中.

How can we mix different input sources when using jq ? For a specific usecase, I'd like to add some data from a file into a feed that was pipe in stdout.

$ echo '[{"a": 1}]' > /tmp/a1
$ echo '[{"a": 2}]' > /tmp/a2
$ jq --slurp '.[0] + .[1]' /tmp/a1 /tmp/a2
[
  {
    "a": 1
  },
  {
    "a": 2
  }
]
$ cat /tmp/a1 | jq --slurp '.[0] + .[1]' /tmp/a2  # Expecting the same result
[
  {
    "a": 2
  }
]

如您所见,最后一个命令没有解释管道数据.

As you can see, the last command didn't interpret the piped data.

现在,我被迫将第一个操作的输出保存到一个临时文件中,以便我可以执行jq合并操作,然后再将其发送回网络.拥有单个流会更有效率

Right now, I'm forced to save the output from the first operation into a temporary file, so that I can do the jq merging operation, before sending it back to the network. Having a single stream would be much more efficient

我想将文件中的某些数据添加到标准输出中通过管道传输的Feed中.

I'd like to add some data from a file into a feed that was pipe in stdout.

有多种方法可以执行此操作,具体取决于外壳以及所使用的jq的版本.

There are various ways to do this, depending on the shell and also the version of jq you are using.

假设您的jq支持--argfile选项,您可能会发现它很合适:

Assuming your jq supports the --argfile option, you might find that quite congenial:

cat /tmp/a1 | jq --argfile a2 /tmp/a2 '. + $a2'

这是另一个变种,它暗示了其他一些可能性:

Here is another variation that suggests some of the other possibilities:

jq -n --argfile a1 <(cat /tmp/a1) --argfile a2 <(cat /tmp/a2) '$a1 + $a2'

更有趣的是:

(cat /tmp/a1 ; cat /tmp/a2) | jq '. + input' 

最后是一种适用于每个jq版本的方法:

And finally an approach that should work for every version of jq:

jq -s '.[0] + .[1]' <(cat /tmp/a1) /tmp/a2

但是,通常最好避免使用-s选项.

In general, though, it's best to avoid the -s option.

如果您比较由以下人员产生的输出:

If you compare the outputs produced by:

echo '1 2' |
  jq -s --debug-dump-disasm --debug-trace  '.[0], .[1]'

echo '1 2' |
  jq --debug-dump-disasm --debug-trace  '., input'

您会注意到,前者必须使用PUSHK_UNDER来存储整个数组[1,2], 而后一个程序只是分别读取两个输入.

you'll notice the former has to PUSHK_UNDER to store the entire array [1,2], whereas the latter program just reads the two inputs separately.

在第一个程序中,要等到之后才能释放阵列的内存 指向它的所有指针都已被处理,而在第二个程序中, 的记忆.可以在第一个RET之后释放.

In the first program, the memory for the array cannot be freed until after all the pointers into it have been processed, whereas in the second program, the memory for . can be freed after the first RET.