![](/img/trans.png)
[英]How do I insert a bash variable into the JSON body of a cURL request?
[英]Replace JSON body in Curl request from stdin bash
我正在嘗試使用來自stdin的輸入在curl請求的主體中填充一個變量。
echo 123 | curl -d "{\\"query\\": {\\"match\\": {\\"number\\": @- }}}" -XPOST url.com
不幸的是, @-
沒有被替換。 我希望請求的內容與以下內容匹配
{
"query": {
"match": {
"number": 123
}
}
}
如何替換標准輸入中的query.match.number
值?
就像您在這里嘗試的那樣,curl不會僅從stdin中讀取文檔的子集-它要么從stdin中讀取整個內容,要么不從stdin中讀取它。 (如果它達到了您的期望,則不可能在不引入轉義/轉義行為的情況下,將文字字符串@-
放入傳遞給curl -d
的文檔文本中,從而使行為進一步復雜化)。
要生成使用stdin中的值的JSON文檔,請使用jq
:
echo 123 |
jq -c '{"query": { "match": { "number": . } } }' |
curl -d @- -XPOST url.com
就是說,根本沒有令人信服的理由在這里使用stdin。 考慮改為:
jq -nc --arg number '123' \
'{"query": { "match": { "number": ($number | tonumber) } } }' |
curl -d @- -XPOST url.com
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.