Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

bash - Passing JSON arguments (not simple strings) to jq

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
' "$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
}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...