0

I am new to shell script, I am trying to substitute an array inside an object but its not working.

I am trying to make curl request with dynamic data payload.

case $name in
  "test1")
      VALUE='[{"test": "1"},{"test": "2"}]'
      ;;
  "test2")
      VALUE='[{"test": "1"},{"test": "3"}]'
      ;;
  ?)
      echo "Error"
      exit 1
      ;;
  esac

I am doing a curl like

$(curl -s -X POST \
        "${BASE_URL}/pdc/config/add" \
        -H "authorization: Bearer ${TOKEN}" \
        -H "content-type: application/json" \
        -d '{
            "data": '\"${VALUE}\"'
            }' \
        --insecure
)

But this sends the array as a string.

The data to be sent should be like

{"data": [{"test": "1"},{"test": "3"}]}

But right now it is being sent as

{"data": "[{"test": "1"},{"test": "3"}]"}

How can I fix this?

Tony Roczz
  • 2,366
  • 6
  • 32
  • 59
  • 1
    Constructing JSON by sticking strings together is a good way to wind up with bad syntax. You're generally better off using a tool that knows how to get the syntax right, like `jq`. – Gordon Davisson May 21 '20 at 16:50
  • This code has no arrays in it anywhere whatsoever. A shell array looks like `array=( "first value" "second value" )`, and it's a `bash`-only feature not available in `sh` at all. The shell doesn't know JSON *exists*, much less what a JSON array looks like. – Charles Duffy May 21 '20 at 17:55
  • ...whereas if you *did* have an actual bash array and wanted to make a JSON array out of it, we have an existing, answered question telling you how to do that: [How to format a bash array as a json array](https://stackoverflow.com/questions/26808855/how-to-format-a-bash-array-as-a-json-array) – Charles Duffy May 21 '20 at 17:56
  • 2
    BTW, don't put `$( ... )` around your command without a good reason to. With curl, that's outright dangerous -- it lets the remote server send back a string your local shell will word-split, glob-expand, *and then run as a local command*, so whoever runs the server (or is doing a MITM attack against it, or against your network connection, since you're using `--insecure`) can run code on your machine. – Charles Duffy May 21 '20 at 17:57

1 Answers1

1

The -d option should be:

-d '{"data": '"${VALUE}"'}'

It expands to

-d {"data": [{"test": "1"},{"test": "3"}]}

For the shell, $VALUE (or, equivalently, ${VALUE}) is a string.

Quasímodo
  • 3,812
  • 14
  • 25