重用散列键并生成 csv 就绪格式

Reuse the hash-key and generate csv ready format

我正在尝试使用 jq 创建一个 csv 就绪输出,并希望在途中重用嵌套的哈希键。

在此示例中,应重新使用 http、https 来生成 csv 就绪格式 ([][]...)

原创

{
   "google.com":{
      "https":{
         "dest_url":"http://aaa.com"
      }
   },
   "microsoft.com":{
      "http":{
         "dest_url":"http://bbb.com"
      },
      "https":{
         "dest_url":"http://ccc.com"
      }
   }
}

预计

[
  "https://google.com",
  "http://aaa.com"
]
[
  "http://microsoft.com",
  "http://bbb.com",
]
[
  "https://microsoft.com",
  "http://ccc.com"
]

我试过的

to_entries[] | [.key, .value[].dest_url]
[
  "google.com",
  "http://aaa.com"
]
[
  "microsoft.com",
  "http://bbb.com",
  "http://ccc.com"
]

如果您将访问 .key 和迭代 .value[] 分开,您将得到笛卡尔积:

jq 'to_entries[] | [.key] + (.value[] | [.dest_url])'
[
  "google.com",
  "http://aaa.com"
]
[
  "microsoft.com",
  "http://bbb.com"
]
[
  "microsoft.com",
  "http://ccc.com"
]

Demo


要包含嵌套键,在使用内部 to_entries:

下降之前保存外部 .key 更容易
jq 'to_entries[] | .key as $key | .value | to_entries[] | [.key + "://" + $key, .value.dest_url]'
[
  "https://google.com",
  "http://aaa.com"
]
[
  "http://microsoft.com",
  "http://bbb.com"
]
[
  "https://microsoft.com",
  "http://ccc.com"
]

Demo