【问题标题】:JSON file to CSV file conversion when my JSON columns are dynamic当我的 JSON 列是动态的时,JSON 文件到 CSV 文件的转换
【发布时间】: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


    【解决方案1】:

    只需使用keys_unsorted(或keys,如果您希望它们排序)。参见例如Convert JSON array into CSV using jqHow to convert arbitrary simple JSON to CSV using jq? 用于两个 SO 示例。还有很多其他的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多