iOSGuy
iOSGuy

Reputation: 61

Passing a shell variable to a JSON request to curl?

Let's take the following example:

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

Now I want to have the boolean value of "item" be set in a shell script variable such as:

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

And I want to pass in the value of PRIVATE to item. I have tried every which way but no luck. Can anyone shed some light?

Upvotes: 3

Views: 3948

Answers (3)

Karl Pokus
Karl Pokus

Reputation: 810

This abomination works too.

$ npm run script -- madrid

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

Upvotes: 0

Wenbing Li
Wenbing Li

Reputation: 12952

You can do it this way:

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

Upvotes: 3

GUESTGUESTGUEST
GUESTGUESTGUEST

Reputation: 11

Instead of your existing -d ... line above, you could try the following:

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

That is: when using double quote speechmarks ("), bash substitutes values for variables referenced $LIKE_THIS (not the case for single quotes you were using). The downside is that you then need to escape any double-quotes in the string itself (using the backslash, as above).

Upvotes: 1

Related Questions