将JSON行转换为TSV,为每个数组项生成单独的行。

huangapple go评论67阅读模式
英文:

Convert json-lines to tsv, producing a separate line for each array item

问题

Sure, here's the translated part:

我有以下的输入文件:

["alice", ["foo", "bar", "baz"]]
["bob", ["qux", "quux"]]
⋮

我想将其转换成一个制表符分隔的文件,如下所示(请注意没有引号):

alice   foo
alice   bar
alice   baz
bob     qux
bob     quux
⋮

所有的数组元素都保证是字符串(不会有空值)。
你需要帮我设计一个 jq 脚本来实现这个吗?

英文:

I have the following input file

["alice", ["foo", "bar", "baz"]]
["bob", ["qux", "quux"]]
⋮

and I want to convert it to a tab separated file that looks like the following (note the lack of quotes)

alice   foo
alice   bar
alice   baz
bob     qux
bob     quux
⋮

All the array elements are guaranteed to be strings (no nulls).
Can you help me come up with a jq script to achieve this?

答案1

得分: 3

替换last项目(或等效地,.[1]项目)为其自身的每个项目(.[]),然后使用@tsv将所有内容转换为制表符分隔的值:

jq -r 'last = last[] | @tsv' input.json
alice	foo
alice	bar
alice	baz
bob	qux
bob	quux

演示

英文:

Replace the last item (or equally the .[1] item) with each of its own items (.[]), then turn all of it into tab-separated values using @tsv:

jq -r 'last = last[] | @tsv' input.json
alice	foo
alice	bar
alice	baz
bob	qux
bob	quux

Demo

答案2

得分: 2

这是另一种通过将第一个元素放入数组然后使用内建的 combinations 来完成的方法。

jq --raw-output '.[0]=[.[0]] | combinations | @tsv' input.json

jqplay.org 上尝试。

英文:

Here's another way to do it by placing the first element in an array and then using the built-in combinations.

jq --raw-output '.[0]=[.[0]] | combinations | @tsv' input.json

Try it on [jqplay.org](https://jqplay.org/s/0jRNnm3RdVH "Click me!").

huangapple
  • 本文由 发表于 2023年6月8日 17:00:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定