jq 对象构造中的 Zip 列表通过 {} 而不是像默认值一样将它们相乘 [英] Zip lists in jq's objects construction by {} instead of multiplying them like default

查看:23
本文介绍了jq 对象构造中的 Zip 列表通过 {} 而不是像默认值一样将它们相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样的 JSON 对象:

A JSON object like this:

{"user":"stedolan","titles":["JQ Primer", "More JQ"],"years":[2013, 2016]}

而且,我想用列表(假设所有列表的长度相同N)来转换它并像这样输出:

And, I want to convert it with lists(assume all lists have equal length N) zipped and output like this:

{"user":"stedolan","title":"JQ Primer","year":2013}
{"user":"stedolan","title":"More JQ","year":2016}

我按照 Object - {} 示例进行了尝试:

I followed Object - {} example and tried:

tmp='{"user":"stedolan","titles":["JQ Primer", "More JQ"],"years":[2013, 2016]}'
echo $tmp | jq '{user, title: .titles[], year: .years[]}'

然后输出:

{"user":"stedolan","title":"JQ Primer","year":2013}
{"user":"stedolan","title":"JQ Primer","year":2016}
{"user":"stedolan","title":"More JQ","year":2013}
{"user":"stedolan","title":"More JQ","year":2016}

它产生 N*N ... 行结果,而不是 N 行结果.

It produces N*N ... lines result, instead of N lines result.

感谢任何建议!

推荐答案

transpose/0 可用于有效地将值压缩在一起.赋值方式的好处在于它可以同时赋值给多个变量.

transpose/0 can be used to effectively zip the values together. And the nice thing about the way assignments work is that it can be assigned simultaneously over multiple variables.

([.titles,.years]|transpose[]) as [$title,$year] | {user,$title,$year}

如果您希望结果是数组而不是流,只需将其全部包装在 [] 中.

If you want the results in an array rather than a stream, just wrap it all in [].

https://jqplay.org/s/ZIFU5gBnZ7

对于 jq 1.4 兼容版本,您必须重写它以不使用解构,但您可以使用内置函数中相同的 transpose/0 实现.

For a jq 1.4 compatible version, you'll have to rewrite it to not use destructuring but you could use the same transpose/0 implementation from the builtins.

transpose/0:

def transpose:
  if . == [] then []
  else . as $in
  | (map(length) | max) as $max
  | length as $length
  | reduce range(0; $max) as $j
      ([]; . + [reduce range(0;$length) as $i ([]; . + [ $in[$i][$j] ] )] )
            end;

这是我编写的一个替代实现,它也应该兼容.:)

Here's an alternative implementation that I cooked up that should also be compatible. :)

def transpose2:
    length as $cols
      | (map(length) | max) as $rows
      | [range(0;$rows) as $r | [.[range(0;$cols)][$r]]];

([.titles,.years]|transpose[]) as $p | {user,title:$p[0],year:$p[1]}

这篇关于jq 对象构造中的 Zip 列表通过 {} 而不是像默认值一样将它们相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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