2

When I try to submit this, the sever sends me back the message

"Unexpected token t in JSON at position 1".

And it'll do that with whatever the first non { non " character is. If I input {"": ""} it'll say

"Unexpected token : in JSON at position 1".

This is my code .

  curl -H "Content-Type: application/json" -d {"test": "test"} url

I've tried other variants of putting quotes around it and escaping quotes to no avail, but if you think that's the issue feel free to suggest a format.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Mason
  • 738
  • 7
  • 18
  • As for cURL and Bash accepting it on command line, this `-d '{"test": "test"}'` worked for me. Try removing the space after the colon to satisfy JSON validation on server side. – marekful Dec 19 '17 at 05:39

1 Answers1

7

You need to protect the double quotes as well as the spaces. You can do so with single quotes, thus:

curl -H "Content-Type: application/json" -d '{"test": "test"}' url

Without the single quotes, shell treats the double quotes as a part of the syntax and strips them, and hence curl would only see

{test:

as the argument for -d option, and

test}

is sent as a separate argument. With the double quotes in place, curl will see this as the argument to -d:

{"test": "test"}

You can also achieve this with backslashes, which is a little cumbersome:

curl -H "Content-Type: application/json" -d {\"test\":\ \"test\"} url

See these related posts / documentation:

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • 1
    Wow, thank you so much. That was like the one thing I didn't try. Why does that work but not {\"test\": \"test\"} – Mason Dec 19 '17 at 05:51
  • With `\`, you are able to protect the double quotes. However, you are not protecting the space. {\"test\":\ \"test\"} should work. – codeforester Dec 19 '17 at 05:58
  • 1
    In more detail, if you don't quote the space, the argument to `-d` is `{"test":` and the argument after the space is separate. – tripleee Dec 19 '17 at 06:02
  • 1
    Maybe see also https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable – tripleee Dec 19 '17 at 06:03