Search code examples
jsonjqparent

jq query to find nested value and return parent values


having trouble finding this, maybe it's just my search terms or who knows.

basically, i have a series of arrays mapping keyspaces to destination DBs for a large noSQL migration, in order for us to more easily script data movement. i'll include sample JSON below.

it's nested basically like: environment >> { [ target DB ] >> [ list of keyspaces ] }, { [ target DB ] >> [ list of keyspaces ] }

my intent was to update my migration script to more intelligently determine where things go based on which environment is specified, etc and require less user input or "figuring things out".

here's sample JSON:

{
    "Prod": [
        {
            "prod1": [
                "prod_db1",
                "prod_db2",
                "prod_d31",
                "prod_db4"
            ]
        },
        {
            "prod2": [
                "prod_db5",
                "prod_db6",
                "prod_db7",
                "prod_db8"
            ]
        }
    ]
}

assuming i'm able to provide keyspace and environment to the script, and use those as variables in my jq query, is there a way to search for the keyspace and return the value for one level up? IE, i know i can do something like:

!#/bin/bash
ENV="Prod"
jq '.."${ENV}"[][]' env.json

to just get the DBs in the prod environment. but if i'm searching for prod_db6' how can i return the value prod2`?


Solution

  • Use to_entries to decompose an object into an array of key-value pairs, then IN to search in the value's array, and finally return the key:

    jq -r --arg env "Prod" --arg ksp "prod_db6" '
      .[$env][] | to_entries[] | select(IN(.value[]; $ksp)).key
    ' env.json
    
    prod2
    

    Demo