Home > Enterprise >  Reuse the hash-key and generate csv ready format
Reuse the hash-key and generate csv ready format

Time:03-05

I'm trying to create an csv ready output with jq, and want to reuse the nested hash key on the way.

In this example http, https should be reused to generate csv ready format ([][]...).

Original

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

Expected

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

What I tried

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

CodePudding user response:

If you separate accessing .key and the iteration over .value[], you'll get the cartesian product:

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

Demo


To include the nested keys, it's easier to save the outer .key before descending with the inner to_entries:

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

  • Related