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

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

问题描述

我想转换对象流:

<代码>{"a": "绿色",b":白色"}{"a": "红色",c":紫色"}

合并为一个对象:

<代码>{"a": "红色","b": "白色",c":紫色"}

另外,如何将相同的序列包装成一个数组?

<预><代码>[{"a": "绿色",b":白色"},{"a": "红色",c":紫色"}]

遗憾的是,手册严重缺乏全面性,谷歌搜索也找不到答案.

解决方案

如果你的输入是一个对象流,那么除非你的 jq 有 inputs,否则这些对象必须被slurped",例如使用 -s 命令行选项,以便将它们组合起来.

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

jq -s 添加

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

jq -s .

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

高效的解决方案

对于第一个问题(reduce),比起slurping(无论是通过-s选项,还是使用[inputs]),使用reduce会更有效率> 带有 inputs 和 -n 命令行选项.例如,要将对象流合并为单个对象:

jq -n '将输入减少为 $in (null; . + $in)'

等价地,没有--null-input:

jq '将输入减少为 $in (.; . + $in)

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.

解决方案

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 .

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

Efficient solution

For the first problem (reduction), 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)'

Equivalently, without --null-input:

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

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

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