简体   繁体   English

使用 jq 嵌套 JSON 到 TSV 的可变键

[英]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带有变量关键字( lab001lab002等),我想使用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 ID T1 T1 T2 T2 T3 T3
lab001实验室001 k26,e23 k26,e23 s92 s92
lab002实验室002 t32,y55 t32,y55 q78 q78 b24 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

Online demo在线演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM