Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON::ParserError: A JSON text must at least contain two octets! (for non-nil input)

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.

like image 805
MalcolmOcean Avatar asked Feb 16 '23 22:02

MalcolmOcean


1 Answers

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
like image 86
Joe Frambach Avatar answered Mar 05 '23 17:03

Joe Frambach