Dominik
Dominik

Reputation: 90

How to select values of keys that are provided as variables in jq?

If this was the input,

{
    "a_key":        2,
    "another_key":  100,
    "one_more_key": -4.2
}

what would be the best way to select the value of any of these keys by providing the name of the key as a variable? Ideally, I was looking for something like:

"a_key" as $key | .$key

This result in a syntax error, though ("unexpected '$'"). I could not figure out a straightforward way to make jq evaluate the variable.

Upvotes: 0

Views: 1921

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134571

Just like in javascript, jq supports indexing. You can access properties by name on objects.

"a_key" as $key | .[$key]

Upvotes: 2

Dominik
Dominik

Reputation: 90

After playing around a bit, I came up with this function, which does the trick, by converting keys into values using "to_entries":

def val(key):
    key as $key | 
    to_entries | 
    .[] | select(.key == $key) | 
    .value;

"a_key" as $key | val($key) # outputs 2

Still, I feel there should be a simpler solution.

Upvotes: 0

Related Questions