How to select values of keys that are provided as

2019-03-05 08:22发布

问题:

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.

回答1:

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

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


回答2:

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.