Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 299
Eqbal Avatar asked Mar 11 '12 22:03

Eqbal


1 Answers

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.

like image 92
d11wtq Avatar answered Nov 08 '22 10:11

d11wtq