4

I'm trying to send a POST request with curl, but I'd like to store the json data in a variable in order to resend it if an error occur. I used this code:

jsonvariable="{"ora" : "value1", "temp" : "value2", "rh" : "value3", "lat" : "value4", "longi" : "value5"}"


curl -X POST -H "Content-Type: application/json" -d '$jsonvariable' http://localhost:8080/updates

but the format after the -d option is not correct. Can you help me?

this code:

curl -X POST -H "Content-Type: application/json" -d '{"ora" : "value1", "id" : "value2", "temp" : "value3","rh" : "value4", "lat" : "value5", "longi" : "value6"}' http://localhost:8080/updates

gives no errors instead

dessert
  • 39,982
yuki182
  • 43

1 Answers1

6

You used single quotes which prevent the variable from being expanded. Use double quotes instead:

curl -H "Content-Type: application/json" -d "$jsonvariable" http://localhost:8080/updates

If your variable content contains double quotes you can quote them with e.g. backslashes.

You can omit -X POST here because POST is the default method if you specify data to send with -d.

Further reading on quoting in bash: How do I enter a file or directory with special characters in its name?

dessert
  • 39,982
  • 2
    That's reducing the problem to a more difficult one. How do I properly escape $jsonvariable then? – Dirk Groeneveld Mar 20 '20 at 22:57
  • @DirkGroeneveld How is proper quotation a more difficult problem? It seems like you have a new question, if so please ask it: Ask Question. – dessert Mar 21 '20 at 06:52
  • That's not fair @dessert, that's a part of this question, at least it should be part of your answer otherwise your answer is incomplete. If every SO answer was like this there'd be 10 times as many questions asked and everyone would get frustrated. It's nice of you to try to provide an answer, but your attempt is very short and clearly incomplete. – NeilG Dec 02 '22 at 11:11