将Shell变量传递给curl的JSON请求?

3

让我们来看下面的例子:

curl -i -X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "Player.Open", "params":{"item":false}}' \
http://example.com/jsonrpc

现在我想要将“item”的布尔值设置为一个shell脚本变量,例如:
 PRIVATE=false
 read -p "Is this a private? (y/[n]) " -n 1 -r
 if [[ $REPLY =~ ^[Yy]$ ]]; then
     PRIVATE=true
 fi

我希望将PRIVATE的值传递给item。我已经尝试了各种方法,但是没有成功。有人可以给予一些提示吗?


1
-d '....{"item":'"$PRIVATE"'}}' - Etan Reisner
3个回答

3
您可以这样做:
curl -i -X POST \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "Player.Open", "params":{"item":'"$PRIVATE"'}}' \
http://example.com/jsonrpc

1

与其使用上面的-d ...行,您可以尝试以下操作:

-d "{\"jsonrpc\": \"2.0\", \"method\": \"Player.Open\", \"params\":{\"item\":$PRIVATE}}" \

也就是说,当使用双引号语言标记(")时,bash将替换变量$LIKE_THIS的值(您使用单引号时不会发生这种情况)。缺点是您需要转义字符串本身中的任何双引号(使用反斜杠,如上所示)。


0

这个可怕的东西也能工作。

$ npm run script -- madrid

# script
json='{"city":"'"$1"'"}'
curl -X POST -d $json http://localhost:5678/api/v1/weather

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接