简体   繁体   中英

jq extract value of keypair and assign to bash variable

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

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM