mmajis
mmajis

Reputation: 545

jq: How to look up a JSON object by name read from another object?

I have the following JSON:

{
    "contexts": {
        "context1": {
            "mydata": "value1"
        },
        "context2": {
            "mydata": "value2"
        }
    },
    "current_context": "context2"
}

I'd like to use jq to output the value of mydata for the context indicated by current_context. The above would output value2. If I change the JSON to have "current_context": "context1", I'd get value1.

Given two invocations of jq, and the above JSON content in a file called jq.json, this works:

jq -r --arg context "$(jq -r '.current_context' jq.json)" '.contexts | to_entries[] | select(.key == $context) | .value.mydata' jq.json

Is there a way to do this with a single invocation of jq?

Thanks!

Upvotes: 0

Views: 108

Answers (2)

Dmitry
Dmitry

Reputation: 1293

and here's an alternative to jq solution, based on a walk-path unix utility jtc:

bash $ jtc -w'[current_context]<cc>v[^0]<cc>t[mydata]' file.json
"value2"
bash $ 

walk path (-w) breakdown:

  • [current_context]<cc>v - get to the current_context value and memorize it in the namespace cc (directive <cc>v does it)
  • [^0]<cc>t[mydata] - reset walk path back to root ([^0]) and recursively search for the label (tag) stored in the namespace (<cc>t), then address found JSON object by label mydata.

PS> Disclosure: I'm the creator of the jtc - shell cli tool for JSON operations

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158060

Like this:

jq -r '.contexts[.current_context].mydata' file.json

You could also use a variable:

jq -r '.current_context as $cc|.contexts[$cc].mydata' file.json

Upvotes: 2

Related Questions