Nathan Hoad

How to: Return JSON from Sinatra

It's so easy to output JSON from Sinatra it will take longer to read this post than to actually do it

First, make sure you have the 'json' gem:

sudo gem install json

Then require it in your Sinatra application:

require 'json'

Now all you have to do is spit out some JSON using the to_json method provided by the gem. Here is a simple example to try it out:

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

It's that simple

If I just made your day a little better then thank me with a coffee: