0

I am trying to pass bash variables to the cURL request body. I've tried different ways of formatting the string in order for variables to be expanded, however, the JSON is not parsed. Could anyone please help me with this?

IP = $1
TOTAL = $2

curl -s -H "Content-Type: application/json" -X POST -d '{"total" : $TOTAL, "ip" : $2}' http://localhost:3000/start
  • This is at least a near-duplicate of ["Create a valid JSON string from either Bash or Ruby?"](https://stackoverflow.com/questions/54023812/create-a-valid-json-string-from-either-bash-or-ruby), ["Curl quotes and variable trouble"](https://stackoverflow.com/questions/58028474/curl-quotes-and-variable-trouble), and ["Difference between single and double quotes in Bash"](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) (and probably others). – Gordon Davisson Nov 02 '20 at 05:13

2 Answers2

4

To be sure to send correct JSON strings, it is better to generate the JSON data with jq:

#!/usr/bin/env bash

json_data=$(
  jq \
  --null-input \
  --compact-output \
  --arg total "$1" \
  --arg ip "$2" \
  '{"total" : $total, "ip" : $ip}'
)

curl \
  --silent \
  --request POST \
  --header 'Content-Type: application/json' \
  --data "$json_data" \
  http://localhost:3000/start
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
1

It might be on the node(?) side ... - this should get the data passed through cURL okay

#!/bin/bash
IP=$1
TOTAL=$2
JSON='{"total" : "'"$TOTAL"'", "ip" : "'"$2"'"}'
curl -s -H "Content-Type: application/json" -X POST -d "'$JSON'" https://localhost:3000/start
user2182349
  • 9,569
  • 3
  • 29
  • 41