简体   繁体   中英

Ruby / sinatra - How to ouput JSON

I'm trying to format my output as json. Here is a test code from http://www.sinatrarb.com/contrib/json.html :

require "sinatra"
require "sinatra/json"

# define a route that uses the helper
get '/' do
  json :foo => 'bar'
end

# The rest of your classic application code goes here...

It shows me an "Application Error". Maybe it comes from the other files to launch the app. I'm using heroku(cloud). So I have a Gemfile :

source 'https://rubygems.org'
gem 'sinatra', '1.1.0'
gem 'thin'

Gemfile.lock :

GEM
  remote: https://rubygems.org/
  specs:
    daemons (1.1.9)
    eventmachine (1.0.3)
    rack (1.5.2)
    sinatra (1.1.0)
      rack (~> 1.1)
      tilt (~> 1.1)
    thin (1.5.1)
      daemons (>= 1.0.9)
      eventmachine (>= 0.12.6)
      rack (>= 1.0.0)
    tilt (1.4.1)

PLATFORMS
  ruby

DEPENDENCIES
  sinatra (= 1.1.0)
  thin

and Procfile :

web: bundle exec ruby web.rb -p $PORT

Did I miss something ?

You need to reference in your Gemfile json gem, eg:

gem "json", "1.5.5"

And then you call .to_json on the object you want to output as JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM