10

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

Eqbal
  • 1,819
  • 2
  • 16
  • 25

1 Answers1

23

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.

d11wtq
  • 34,788
  • 19
  • 120
  • 195