Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reuse the hash-key and generate csv ready format

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
   "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"
]

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading