【问题标题】:Passing a shell variable to a JSON request to curl?将 shell 变量传递给 JSON 请求以进行 curl?
【发布时间】:2014-08-14 03:08:58
【问题描述】:

我们来看下面的例子:

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

现在我想在 shell 脚本变量中设置“item”的布尔值,例如:

 PRIVATE=false
 read -p "Is this a private? (y/[n]) " -n 1 -r
 if [[ $REPLY =~ ^[Yy]$ ]]; then
     PRIVATE=true
 fi

我想将 PRIVATE 的值传递给项目。我已经尝试了所有方法,但没有运气。有人能解释一下吗?

【问题讨论】:

  • -d '....{"item":'"$PRIVATE"'}}'

标签: json bash curl


【解决方案1】:

你可以这样做:

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

【讨论】:

    【解决方案2】:

    您可以尝试以下操作,而不是上面现有的 -d ... 行:

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

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

    【讨论】:

      【解决方案3】:

      这种可憎的东西也有效。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-28
        • 1970-01-01
        • 2018-07-14
        • 2013-11-02
        • 2013-05-04
        • 1970-01-01
        相关资源
        最近更新 更多