1

How do I pass in bash variables into a jq --arg parameter?

All I can get to work is this:

FINAL_JSON= #some JSON

PAYLOAD=$(echo $FINAL_JSON | jq ' {
"attachments": .
} ')

What's bothering me is that echo $FINAL_JSON thing. I should be able to pass in variables in jq??

PAYLOAD=$(jq -n --arg attach "$FINAL_JSON" '{ 
"attachments":$attach
}')

But all that does is pass the JSON in as a string. Without quotes " around the $FINAL_JSON I get this error:

error: syntax error, unexpected $end
{1 compile error
12
  • 2
    in general, always quote your echo --> echo "$FINAL_JSON" Commented Jun 2, 2015 at 14:59
  • yea, I don't even wanna echo tho Commented Jun 2, 2015 at 15:01
  • What's the meaning of FINAL_JSON=$(jq -n '[]') ? It simply returns a literal [] . What means # add stuff to FINAL_JSON ? Commented Jun 2, 2015 at 15:04
  • 1
    I'm still not able to get your question. Can you add one self-contained example which shows how do you not want to do it and one self-contained example which you want it to look like? (The latter can be pseudo code or course, since you don't have it already) Commented Jun 2, 2015 at 15:12
  • 1
    @cmbuckley, needs more quotes. <<<"$FINAL_JSON". Commented Jun 2, 2015 at 15:15

1 Answer 1

3

A simple transformation of your working code (also moving to lower-case variable names, as per convention for variable names not reserved for shell or system use):

payload=$(jq -n --argfile attach <(printf '%s\n' "$final_json") '{ 
"attachments":$attach
}')

I'm sticking with --argfile here since it parses the file's contents as JSON; using --arg wouldn't have that effect.

The <(...) syntax is process substitution, which is replaced with a filename for a named pipe or temporary file connected to the content in question.


However, you can also use --arg, and apply the fromjson filter to parse as JSON:

payload=$(jq -n --arg attach "$final_json" '{ 
"attachments":$attach|fromjson
}')
Sign up to request clarification or add additional context in comments.

1 Comment

--argjson is also an option, if you're using 1.5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.