Sunday, January 28, 2024

[SOLVED] How to use variables inside data-raw json string in a curl command

Issue

The following script of curl command works fine with variables inside double-quoted string, but how do I use variables (e.g. ip_address and user_id) inside the --data-raw '{...}'?

#!/bin/sh

ip_address="10.0.0.1"
user_id="my-user-id"
websec_token="some_string"
version="v12"

curl -w @curl-format.txt \
    --request POST "http://example.com/$version/web" \
    --header "Authorization: Bearer $websec_token" \
    --header "Content-Type: application/json" \
    --data-raw '{
        "ipAddress": "10.0.0.1",
        "userId": "my-user-id"
    }'

Solution

Just escape the double quotes:

--data-raw "{
    \"ipAddress\": \"$ip_address\",
    \"userId\": \"$user_id\"
}"


Answered By - dan
Answer Checked By - Clifford M. (WPSolving Volunteer)