json 如何将jq中的一系列对象组合成一个对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34477547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:11:47  来源:igfitidea点击:

How to combine the sequence of objects in jq into one object?

arraysjsonadditionjqfileslurp

提问by Jennifer M.

I would like to convert the stream of objects:

我想转换对象流:

{
  "a": "green",
  "b": "white"
}
{
  "a": "red",
  "c": "purple"
}

into one object:

成一个对象:

{
  "a": "red",
  "b": "white",
  "c": "purple"
}

Also, how can I wrap the same sequence into an array?

另外,如何将相同的序列包装到数组中?

[
    {
      "a": "green",
      "b": "white"
    },
    {
      "a": "red",
      "c": "purple"
    }
]

Sadly, the manual is seriously lacking in comprehensiveness, and googling doesn't find the answers either.

可悲的是,手册严重缺乏全面性,谷歌搜索也找不到答案。

回答by peak

If your input is a stream of objects, then unless your jq has inputs, the objects must be "slurped", e.g. using the -s command-line option, in order to combine them.

如果您的输入是一个对象流,那么除非您的 jq 有inputs,否则必须“slurped”这些对象,例如使用 -s 命令行选项,以便组合它们。

Thus one way to combine objects in the input stream is to use:

因此,在输入流中组合对象的一种方法是使用:

jq -s add

For the second problem, creating an array:

对于第二个问题,创建一个数组:

jq -s .

There are of course other alternatives, but these are simple and do not require the most recent version of jq. With jq 1.5 and later, you can use 'inputs', e.g. jq -n '[inputs]'

当然还有其他选择,但这些都很简单,不需要最新版本的 jq。对于 jq 1.5 及更高版本,您可以使用“输入”,例如jq -n '[inputs]'

Efficient solutions

高效的解决方案

Rather than slurping (whether via the -s option, or using [inputs]), it would be more efficient to use reducewith inputsand the -n command-line option. For example, to combine the stream of objects into a single object:

而不是啜饮(无论是通过 -s 选项还是使用[inputs]),使用reducewithinputs和 -n 命令行选项会更有效。例如,要将对象流合并为单个对象:

jq -n 'reduce inputs as $in (null; . + $in)'

回答by Evgeny

An alternative to slurping using the -s command-line option is to use the inputsfilter. Like so:

使用 -s 命令行选项 slurping 的替代方法是使用inputs过滤器。像这样:

jq -n '[inputs] | add'

This will produce an object with all the input objects combined.

这将生成一个包含所有输入对象的对象。