[英]Nested JSON with variable keys to TSV using jq
I have the following nested JSON file labs.json
with variable keywords ( lab001
, lab002
, etc.) which I would like to convert into a TSV using jq
:我有以下嵌套的 JSON 文件
labs.json
带有变量关键字( lab001
, lab002
等),我想使用jq
将其转换为 TSV:
{
"lab001": {
"tags": {
"T1": [],
"T2": ["k26","e23"],
"T3": ["s92"]
},
"code": "8231"
},
"lab002": {
"tags": {
"T1": ["t32","y55"],
"T2": ["q78"],
"T3": ["b24"]
},
"code": "9112"
}
}
The resulting table should look like:结果表应如下所示:
ID ![]() |
T1 ![]() |
T2 ![]() |
T3 ![]() |
---|---|---|---|
lab001![]() |
k26,e23 ![]() |
s92 ![]() |
|
lab002![]() |
t32,y55 ![]() |
q78 ![]() |
b24 ![]() |
Currently I am using a rather pedestrian approach by pasting two calls of jq
and doing some cleanup with tr
:目前,我通过粘贴两个
jq
调用并使用tr
进行一些清理来使用一种相当普通的方法:
paste <(jq -r 'keys_unsorted | @csv' labs.json | tr ',' '\n') <(jq -r '.[].tags | map(tostring) | @tsv' labs.json) | tr -d '[]"'
Is there any more elegant way to get this done purely with jq
?有没有更优雅的方法可以纯粹用
jq
完成这项工作?
Join elements of each tag by commas, put resulting strings into an array with the lab ID as the first element, and pipe it to the @tsv
filter like so:用逗号连接每个标签的元素,将生成的字符串放入以实验室 ID 作为第一个元素的数组中,然后将
@tsv
过滤器,如下所示:
keys_unsorted[] as $id | [$id, (.[$id].tags[] | join(","))] | @tsv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.