使用Ruby读取json然后以json的形式输出

时间:2012-05-02 20:29:40

标签: ruby json http file-io cgi

我正在尝试从本地.json文件中读取我返回的信息。如何让ruby从这个文件中返回json信息?到目前为止我所拥有的:

#! /usr/bin/env ruby
require 'json'
require 'cgi'

cgi = CGI::new()

if cgi.request_method == 'GET' then
  json = File.read('path/to/file.json')
  print json
end

1 个答案:

答案 0 :(得分:1)

如果您使用的是Ruby 1.9.3,则没有File.read执行此操作:

if cgi.request_method == 'GET'
    print File.open('path/to/file.json').read
end

此外,您应该使用http://www.ruby-doc.org/stdlib-1.9.3/libdoc/cgi/rdoc/CGI.html#method-i-out

cgi.out("nph"        => true,
    "status"     => "OK",  # == "200 OK"
    "server"     => ENV['SERVER_SOFTWARE'],
    "connection" => "close",
    "type"       => "text/html",
    "charset"    => "iso-2022-jp",
      # Content-Type: text/html; charset=iso-2022-jp
    "language"   => "ja",
    "expires"    => Time.now + (3600 * 24 * 30),
    "cookie"     => [cookie1, cookie2],
    "my_header1" => "my_value",
    "my_header2" => "my_value") { "string" }