Search code examples
ruby-on-railsrubyjsonrackmiddleware

How to response with JSON format using Ruby Rack middleware


How to reply a simple ruby rack server with JSON object , lets assume mt server is something like :

app = Proc.new do |env| 
  [200, { 'Content-Type' => 'text/plain' }, ['Some body']]
end 

Rack::Handler::Thin.run(app, :Port => 4001, :threaded => true)

and lets assume instead of some body text I want a JSON object with something like :

{
"root": [
    {
        "function": null
    }
] 

}

Thanks


Solution

  • Include the "json" gem in your project, and then call #to_json on the Hash:

    app = Proc.new do |env| 
      [200, { 'Content-Type' => 'application/json' }, [ { :x => 42 }.to_json ]]
    end
    

    Note that nil is translated to null in the JSON, if you need null.