Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra json rendering not working as expected

Tags:

ruby

sinatra

I'm having a problem in Sinatra where I can't respond with just a json and I can't find good sinatra docs anywhere, most of things seems outdated.

Anyways, here's the code:

module MemcachedManager
  class App < Sinatra::Base
    register Sinatra::Contrib
    helpers Sinatra::JSON

    get '/' do
      json({ hello: 'world' })
    end
  end
end

MemcachedManager::App.run! if __FILE__ == $0

The response that I do get is:

"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><p>{\"hello\":\"world\"}</p></body></html>\n"

Where it should have been only the json part. Why is it rendering html tags when I didn't ask for it?

like image 702
thiagofm Avatar asked Jan 31 '13 21:01

thiagofm


2 Answers

Have you seen this blog post?

require 'json'

get '/example.json' do
  content_type :json
  { :key1 => 'value1', :key2 => 'value2' }.to_json
end

I would also modify this to:

get '/example.json', :provides => :json do

to stop HTML/XML calls using the route. Since you're using the sinatra-contrib gem, and since Ruby doesn't need all those parens etc, you can also simplify the code you've given as an example to:

require 'sinatra/json'

module MemcachedManager    
  class App < Sinatra::Base
    helpers Sinatra::JSON
    get '/', :provides => :json do
      json hello: 'world'
    end
  end
end

MemcachedManager::App.run! if __FILE__ == $0
like image 159
ian Avatar answered Sep 21 '22 19:09

ian


Try putting

content_type :json

before the json(...) call

like image 39
Ahmed Al Hafoudh Avatar answered Sep 23 '22 19:09

Ahmed Al Hafoudh