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?

4
  • 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. Commented May 21, 2020 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. Commented May 21, 2020 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 Commented May 21, 2020 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. Commented May 21, 2020 at 17:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You deserve that buddy :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.