JSON传递参数(不是简单的字符串),以JQ [英] Passing JSON arguments (not simple strings) to jq
问题描述
我如何通过在bash变量成JQ - ARG
参数
我能得到的工作是这样的:
FINAL_JSON = #some JSON有效载荷= $(回声$ FINAL_JSON | JQ'{
附件。
})
什么是困扰我的是,回声$ FINAL_JSON
的事情。我应该能够在变量传递在 JQ
??
PAYLOAD = $(JQ -n --arg附加$ FINAL_JSON'{
附件:$重视
})
但一切确实是通过JSON作为一个字符串。不带引号围绕
$ FINAL_JSON
我得到这个错误:
错误:语法错误,意想不到的$结束
{1编译错误
您的工作code的一个简单的变换(也正在为小写变量名,按约定不保留壳或系统使用的变量名):
的有效载荷= $(JQ -n --argfile附加≤(printf的'%S \\ n'$ final_json)'{
附件:$重视
})
我与坚持 - argfile
在这里,因为它解析该文件的内容为JSON;使用 - ARG
不会有这种效果
的<(...)
语法过程中替换,替换为连接到有问题的内容命名管道或临时文件的文件名
不过,您也可以使用 - 精氨酸
,并应用 fromjson
过滤器来解析为JSON:
的有效载荷= $(JQ -n --arg附加$ final_json'{
附件:$附加| fromjson
})
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
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
}')
这篇关于JSON传递参数(不是简单的字符串),以JQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!