首页 > 解决方案 > 以值作为标头的 Json 到 CSV 转换

问题描述

我有一个下面的 JSON 文件,需要转换为 CSV 文件,其中一些值作为标题,下面的值应该被填充。下面是示例 json

{
  "environments" : [ {
    "dimensions" : [ {
      "metrics" : [ {
        "name" : "count",
        "values" : [ "123" ]
      }, {
        "name" : "response_time",
        "values" : [ "15.7" ]
      }],
      "name" : "abcd"
    }, {
      "metrics" : [ {
        "name" : "count",
        "values" : [ "456" ]
      }, {
        "name" : "response_time",
        "values" : [ "18.7" ]
      }],
      "name" : "xyzz"
    }

这是我已经尝试过的

jq -r '.environments[].dimensions[] | .name as $p_name | .metrics[] | .name as $val_name | if $val_name == "response_time" then ($p_name,$val_name, .values[])' input.json

预计为

name,count,response_time
abcd, 123, 15.7
xyzz, 456, 18.7

标签: jsonshellcsvjq

解决方案


如果目标是依靠 JSON 本身以“metrics”数组呈现它们的任何顺序提供标头名称,那么请考虑:

.environments[].dimensions
| ["name", (.[0] | .metrics[] | .name)],     # first emit the headers
  ( .[] | [.name, (.metrics[].values[0])] )  # ... and then the data rows
| @csv

推荐阅读