Search code examples
jsonbashenvironment-variablesjq

Passing bash variable to jq


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

#!/bin/sh

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

[email protected]

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

Solution

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

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

    Postscript

    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:

    [email protected]  # not exported
    EMAILID="$EMAILID" jq -n 'env.EMAILID'
    

    The output is a JSON string:

    "[email protected]"
    

    shell arrays

    Unfortunately, shell arrays are a different kettle of fish. Here are two SO resources regarding the ingestion of such arrays:

    JQ - create JSON array using bash array with space

    Convert bash array to json array and insert to file using jq