Ruby Rackミドルウェアを使用してJSON形式で応答する方法
概要
単純な Ruby ラックサーバーに JSON オブジェクトで応答する方法。mt サーバーが次のようなものであると仮定します。
app = Proc.new do |env|
[200, { 'Content-Type' => 'text/plain' }, ['Some body']]
end
Rack::Handler::Thin.run(app, :Port => 4001, :threaded => true)
本文テキストの代わりに、次のような JSON オブジェクトが必要だと仮定します。
{
"root": [
{
"function": null
}
]
}
ありがとう
解決策
プロジェクトに「json」gem を含めて、ハッシュで #to_json を呼び出します。
app = Proc.new do |env|
[200, { 'Content-Type' => 'application/json' }, [ { :x => 42 }.to_json ]]
end
null が必要な場合は、JSON 内で nil が null に変換されることに注意してください。