20

Running the following command from a Windows command line using cURL attempting to post a new document to an existing CouchDB database (named test) fails:

curl -H "Content-Type: application/json" -X POST "http://127.0.0.1:5984/test" -d {"valid":"json"}

It returns the error:

{"error":"bad_request","reason":"invalid_json"}

The JSON is valid so what gives?

skinneejoe
  • 3,921
  • 5
  • 30
  • 45

2 Answers2

18

The answer is related to the formatting of the JSON string on the command line. Even though it is proper JSON when you type it, the command line, it seems, must reformat it before sending it.(Maybe someone else can explain why it does this in more detail.) To fix this you need to escape your quotations in the command line like so:

curl -H "Content-Type: application/json" -X POST "http://127.0.0.1:5984/test" -d {"""valid""":"""json"""}

See the extra quotation marks? This should work and return "ok:true" with an id and revision number.

skinneejoe
  • 3,921
  • 5
  • 30
  • 45
  • 2
    The easiest way to do this is to use single quotes: `-d '{"valid": "json"}'` – Kim Stebel Aug 19 '13 at 14:29
  • 5
    Actually single quotes still throws and invalid json error when I'm using curl from a windows command line prompt. – skinneejoe Aug 19 '13 at 14:57
  • 3
    Use putty against remote machines or cygwin or gitbash if you run locally on a Windows machine. Here's my CouchDB cheat sheet http://macgyverdev.blogspot.se/2013/12/couchdb-on-linux-mint.html – Johan Norén Dec 28 '13 at 09:48
  • 4
    This is kind of an ugly way to do it. I do it like: -d {\"valid\":\"json\"}. Harder to get confused this way... – Lilian A. Moraru May 24 '14 at 17:04
  • 2
    Running your curl commands via the Git Bash is the easiest way if you have it installed, which you probably do if you're reading this. – Josh1billion Dec 09 '15 at 20:23
5

You have to quote also the whole statement to support spaces like: -d "{\"title\":\"There is Nothing Left to Lose\" , \"artist\":\"Foo Fighters\"}"

jst
  • 61
  • 1
  • 1