如何使用Ruby Rack中间件响应JSON格式

Eqb*_*bal 7 ruby json rack middleware ruby-on-rails

如何用JSON对象回复一个简单的ruby rack服务器,让我们假设mt服务器是这样的:

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

Rack::Handler::Thin.run(app, :Port => 4001, :threaded => true)
Run Code Online (Sandbox Code Playgroud)

并假设我想要一个JSON对象而不是一些正文文本,例如:

{
"root": [
    {
        "function": null
    }
] 
Run Code Online (Sandbox Code Playgroud)

}

谢谢

d11*_*wtq 18

在项目中包含"json"gem,然后调用#to_jsonHash:

app = Proc.new do |env| 
  [200, { 'Content-Type' => 'application/json' }, [ { :x => 42 }.to_json ]]
end
Run Code Online (Sandbox Code Playgroud)

请注意,如果需要,nil将转换为nullJSON null.