新手问题 如何将 ruby 的 hash 转为 json 字符串?

supersheep · 2012年12月01日 · 最后由 chenge 回复于 2012年12月02日 · 14063 次阅读

尝试直接 hash.to_json 报 undefined method `to_json' for {"a"=>1}:Hash (NoMethodError) 于是 sudo gem install json Fetching: json-1.7.5.gem (100%) Building native extensions. This could take a while... Successfully installed json-1.7.5 1 gem installed Installing ri documentation for json-1.7.5... Installing RDoc documentation for json-1.7.5...

require 'json' 报 main.rb:3:in `require': no such file to load -- json (LoadError)

然后我就没辙了,求解。

1 楼 已删除

···ruby irb(main):001:0> require 'json' => true irb(main):002:0> hash={:name=>"andyshi",:age=>30} => {:name=>"andyshi", :age=>30} irb(main):003:0> hash => {:name=>"andyshi", :age=>30} irb(main):004:0> hash.to_json => "{\"name\":\"andyshi\",\"age\":30}" irb(main):005:0>

···

require 'json'
h = { 'a' => 1 }
JSON h

Rails 下才可以直接用 to_json

以前使用 crack/json

#3 楼 @woaigithub 嗯,我尝试了,在 irb 下这样写的确是可以的,但是写在文件里去 require 'json'为什么就说无法找到包呢?ruby 的包管理机制是什么样的?gem install json 这句有什么问题么?

前面加一行 require 'rubygems'

你的 ruby 什么版本。早期的需要 require 'rubygems'

在 gemfile 中添加一行 gem 'json'

#7 楼 @zmbacker #8 楼 @chenge 果然,这样就可以了,多谢。我是 lion 上默认的版本,1.8.7。

#9 楼 @woaigithub gemfile 是在哪里的呢?我在项目根目录下放了 gemfile,内容为 source 'http://ruby.taobao.org/' gem 'json' 然后 bundle install,bundle show 显示 Gems included by the bundle:

  • bundler (1.0.21)
  • json (1.7.5) 再 ruby test.rb 还是不起作用,必须要 require 'rubygems' requrie 'json'才行。

似乎是大写开头的 Gemfile,就在根目录。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号