Home > Software design >  how to get parent key by child value with jq
how to get parent key by child value with jq

Time:07-07

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:

[
  "d_usage_65",
  "d_usage_75"
]

CodePudding user response:

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

CodePudding user response:

to_entries and select are the important things here:

$ jq -r --arg t 'D Usage 65 | #site' '.[].alerts | to_entries[] | select(.value.title==$t) | .key'  example.json
d_usage_65
  • Related