asidd asidd - 1 year ago 280
JSON Question

passing bash variable to jq select

I have written a script to retrieve certain value from file.json. It works if i provide value to jq select but variable doesn't seem to work (or I don't know how to use it )


#this works ***
projectID=$(cat file.json | jq -r '.resource[] | select(.username=="") | .id')
echo "$projectID"

#this does not work *** no value is printed
projectID=$(cat file.json | jq -r '.resource[] | select(.username=="$EMAILID") | .id')
echo "$projectID"

Answer Source

Consider also passing in the environment variable (EMAILID) as a jq variable (here also EMAILID, for the sake of illustration):

   projectID=$(cat file.json | jq -r --arg EMAILID "$EMAILID" '.resource[]
                               | select(.username==$EMAILID) | .id')


For the record, another possibility would be to use jq's env function for accessing environment variables. For example, consider this sequence of bash commands:  # not exported

The output is a JSON string:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download