Sinatra json rendering not working as expected
ruby, sinatra
Solution
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
Problem
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?