繁体   English   中英

将平面 JSON 转换为带有列标题的 TSV 文件

[英]Convert a flat JSON to a TSV file with column headers

我正在用 JQ 将一些 JSON 重新格式化为 TSV 文件。 我可以创建仅包含值的 TSV,但我无法弄清楚如何将包含键值的单行作为列标题?

示例输入:

{
"id":"1234",
"host":"6789",
"proto":"UDP",
"location":"Boston",
"timestamp":"2020-12-01T14:18:45.717Z",
"src_ip":"192.168.3.70",
"dest_ip":"8.8.8.8",
"dest_port":53,
"message":"Some Information",
"severity":1,
"details":"Some Details",
"categories":["a","b","c"]
}

所需的 output:

"location\ttimestamp\tsrc_ip\tdest_ip\tdest_port"
"Boston\t2020-12-01T15:13:16.242Z\t10.8.25.63\t10.8.1.3\t445"
"Atlanta\t2020-12-01T15:11:15.929Z\t10.8.25.63\t10.80.1.3\t445"
"Chicago\t2020-12-01T15:09:45.271Z\t10.34.196.12\t10.8.1.3\t445"

这句话让我很接近:

cat input.json | jq  '. | to_entries 
| map(select(.key=="timestamp"), select(.key=="location"), select(.key=="src_ip"), select(.key=="dest_ip"), select(.key=="dest_port"))
| map(.key), map(.value) 
| @tsv'

但是 header 行在 output 中重复:

"location\ttimestamp\tsrc_ip\tdest_ip\tdest_port"
"Boston\t2020-12-01T15:13:16.242Z\t10.8.25.63\t10.8.1.3\t445"
"location\ttimestamp\tsrc_ip\tdest_ip\tdest_port"
"Atlanta\t2020-12-01T15:11:15.929Z\t10.8.25.63\t10.80.1.3\t445"

有没有办法只打印第一行的键,然后只打印剩余行的值,只使用 JQ?

使用@tsv function 将这样的平面 object JSON 制作成 TSV 格式的一种方法是

jq -n ' ["location", "timestamp", "src_ip", "dest_ip", "dest_port"] as $hdr | 
        $hdr, ( inputs | [ .[ $hdr[] ] ] ) | @tsv'

这是有效的,通过重复使用 header 中的关键字段, .[ $hdr[] ]是一个简单的技巧,可以将hdr数组中每个文字字段的值扩展到 object 中的相应值(参见通用 Object 索引) . 通过将其括在方括号中,您可以在数组中获得选定的字段值。 收集此数组和 header 数组后,应用@tsv function 获取表格形式。

jq 播放片段 - 演示

暂无
暂无

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

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