Reputation: 2805
jq does my head in sometimes. Assume you have a json file called emails.json
that looks like this;
[
{
"ParameterKey": "foo1",
"ParameterValue": "bar1"
},
{
"ParameterKey": "foo2",
"ParameterValue": "bar2"
}
]
If I run my bash script (let's call it script.sh
) using the argument foo1, I want to have bar1 assigned to a variable called emailAdd
. Likewise, if I use the argument foo2, I want bar2 assigned.
I thought my script would look like the following, but I'm getting an empty variable.
#!/usr/bin/env bash
EMAIL=$1
emailAdd=$(jq --arg email "$EMAIL" '.[] | select(.ParameterKey=="$email") | .ParameterValue' < emails.json)
echo "address is " $emailAdd
So, running sh script.sh foo1
I would expect address is bar1
, etc
Upvotes: 0
Views: 1389
Reputation: 530920
You pretty much have it correct. You don't need the quotes around $email
, because unlike shell, jq
actually treats that as a variable containing a value, rather than something to expand to arbitrary text. You probably also want to use the -r
option so that the output is bar1
, rather than "bar1"
.
#!/usr/bin/env bash
EMAIL=$1
emailAdd=$(jq -r --arg email "$EMAIL" '.[] | select(.ParameterKey==$email) | .ParameterValue' < emails.json)
echo "address is $emailAdd"
Upvotes: 1