How to react with JSON format using Ruby Rack middleware

How to respond to a simple ruby ​​rack server with a JSON object, suggests that the 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 suppose instead of plain text, I want a JSON object with something like:

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

}

thank

+5
source share
1 answer

Include the json pearl in your project, and then call #to_jsonin Hash:

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

Please note that niltranslates to nullin JSON if you need to null.

+15
source

All Articles