0

我正在尝试读取从本地 .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
4

1 回答 1

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" }
于 2012-05-02T21:15:07.927 回答