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

how to get parent key by child value with jq

I have this example json:

{
    "Server monitoring - Disk, Memory, CPU": {
        "alerts": {
            "d_usage_65": {
                "title": "D Usage 65 | #site"
            },
            "d_usage_75": {
                "title": "D Usage 75 | #site"
            }
        }
    },
    "Categoty 2": {
        "alerts": {
            "thread_count_50": {
                "title": "Thread Count above 50 | #site"
            },
            "upload_manager_thread_count_100": {
                "title": "Thread Count above 100 | #site"
            }
            
        }
    }
}

I am trying to get "d_usage_65" for input "D usage 65 | #site".
This is what I have tried:

.[] | .alerts | select(.[].title == "D Usage 65 | #aidoc_site") | keys

but it returned:

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

[
  "d_usage_65",
  "d_usage_75"
]

>Solution :

You can access keys and values at once using to_entries. For instance:

.[] | .alerts | to_entries[] | select(.value.title == "D Usage 65 | #site").key
d_usage_65

Demo

Another approach could be using tostream:

.[] | .alerts | tostream | select(.[1] == "D Usage 65 | #site")[0][0]
d_usage_65

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