I’ve been trying this for a bit now. I want to loop through all the keys that I pulled out and now want to get the values by looping through those keys in bash.
What I’m trying to do is basically:
I got keys through
keys=$(echo "$tags" | jq -r 'keys[]')
where $tags is a json output
The json which is stored in $tags is
{
"project": "en.wikipedia",
"article": "Talking_Heads_discography",
"granularity": "daily",
"timestamp": "2021092800",
"access": "all-access",
"agent": "all-agents",
"views": 381
}
Now I wanted to loop through all the keys and get the values for further processing. I wanted to do something like
for key in $keys; do
value=$(echo $tags | jq -r .[key])
echo "$key has value $value"
done
Is there an easy way to pass a variable to jq to get the key value
These are the things I tried to pass the variable
for key in $keys; do value=$(echo $tags | jq -r '.[key]'); echo "$key has value $value";done
for key in $keys; do value=$(echo $tags | jq -r '."$key"'); echo "$key has value $value";done
for key in $keys; do value=$(echo $tags | jq -r '."[key]"'); echo "$key has value $value";done
for key in $keys; do value=$(echo $tags | jq -r '.[key]'); echo "$key has value $value";done
for key in $keys;do value=$(echo $tags | jq -r '.[key]'); echo $value;done
for key in $keys;do value=$(echo $tags | jq '.[] | ."$key"' ); echo $value;done
I wanted to do this in bash scripting only
2
Answers
UPDATE
variant @pmf from comment
but he’s not fast
it is better to do it through an associative array
The following illustrates one approach: