JSON::ParserError: A JSON text must at least contain two octets! (for non-nil input)
json, post, ruby, sinatra
Solution
Try something along these lines:
post "/api" do
request.body.rewind # in case someone already read it
data = JSON.parse (request.body.read || '{"name":"Not Given"}')
"Hello #{data['name']}!"
end
Problem
So, I realize two questions have already been asked on this subject, but (unfortunately) my case appears to be different. The Sinatra README says to do the following for POST data: ``` post "/api" do request.body.rewind # in case someone already read it data = JSON.parse request.body.read "Hello #{data['name']}!" end ``` When I try this, I get: ``` JSON::ParserError: A JSON text must at least contain two octets! ``` The other questions deal with a case in which the data is nil, or poorly formatted (`\"` instead of `"`), but mine appears to be good. If I open irb and JSON.parse the exact same string that I'm POSTing, it works just fine. This is the command I'm using for testing: ``` curl -XPOST http://localhost:5000/endpoint --data '{"foo":"bar","blah":"wat","abcdefghijklmnop":"qrstuvwxyz"}' ``` I feel like this should be insanely obvious, because parsing POST data is a really basic thing for a webserver to do. Apparently not though. Edit: If I call `logger.info Hash[params]`, I get: ``` {"{\"foo\":\"bar\",\"blah\":\"wat\",\"abcdefghijklmnop\":\"qrstuvwxyz\"}"=>nil, "splat"=>[], "captures"=>["endpoint"], "resource"=>"endpoint"} ``` ...but I'm not sure if/how that helps.