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

return name of the array that contains certain key with jq

I have the following JSON:

{
  "somekey": "somevalue",
  "blue_services": [
    "service-a",
    "service-b",
    "service-c"
  ],
  "otherkey": "othervalue",
  "red_services": [
    "service-d",
    "service-e",
    "service-f"
  ],
  "black_services": [
    "service-g",
    "service-h",
    "service-i"
  ]
}

I want jq to return the name of the array that contains certain value:

for example:

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

if I look for service-a jq should return blue_services
if I look for service-h jq should return black_services

I manage to extract the arrays that match certain regexp with:

keys[] | select(test ("[aA-zZ]_services"))

But i dont know how to then search inside for a match and return the relevant name, I have also tried piping to contains/has/any

ideally I would like to use a variable to be able to do several searches for service-x

>Solution :

You could use to_entries to get an array of key-value pairs. Search the values using IN, and output the key. Use --arg to import a string from the command-line.

jq -r --arg q "service-a" 'to_entries[] | select(IN($q; .value[]?)).key'
blue_services

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