如何将jq中的对象序列组合为一个对象? [英] How to combine the sequence of objects in jq into one object?

查看:112
本文介绍了如何将jq中的对象序列组合为一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换对象流:

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

变成一个对象:

{
  "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"
    }
]

遗憾的是,该手册严重缺乏全面性,并且使用Google搜索也找不到答案.

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

推荐答案

如果您的输入是对象流,那么除非您的jq具有inputs,否则必须对对象进行打浆",例如使用-s命令行选项,以便将它们组合在一起.

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.

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

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 .

当然还有其他替代方法,但是这些替代方法很简单,不需要最新版本的jq.在jq 1.5及更高版本中,您可以使用输入",例如jq -n '[inputs]'

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]'

与其进行混音(无论是通过-s选项还是使用[inputs]),不如使用reduceinputs和-n命令行选项,效率更高.例如,要将对象流合并为单个对象:

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

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

这篇关于如何将jq中的对象序列组合为一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆