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
end

It's that simple

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


Vinyl Stickers, hand-crafted wooden animals, original paintings, and more
Lilly Piri on Etsy