【发布时间】:2021-02-11 01:22:12
【问题描述】:
我找到了 json 到 csv 转换的解决方案。下面是示例 json 和解决方案。
{
"took" : 111,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "alerts",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"alertID" : "639387c3-0fbe-4c2b-9387-c30fbe7c2bc6",
"alertCategory" : "Server Alert",
"description" : "Successfully started.",
"logId" : null
}
},
{
"_index" : "alerts",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"alertID" : "2",
"alertCategory" : "Server Alert",
"description" : "Successfully stoped.",
"logId" : null
}
}
]
}
}
解决办法:
jq -r '.hits.hits[]._source | [ "alertID" , "alertCategory" , "description", "logId" ], ([."alertID",."alertCategory",."description",."logId" // "null"]) | @csv' < /root/events.json
这个解决方案的问题是我必须对列名进行硬编码。如果我的 json 稍后在 _source 标签下添加了一些内容怎么办?我需要一个可以处理_source 下的动态数据的解决方案。我对 shell 中的任何其他工具或命令持开放态度。
【问题讨论】:
标签: json shell csv export-to-csv jq