今天遇到了一個要解析JSON的需求。在http://stackoverflow.com/questions/1826727/how-do-i-parse-json-with-ruby-on-rails找到了答案。
irb(main):021:0> arr=JSON.parse str_vps
=> [{"id"=>"260e053b-d728-4785-888d-eb4f1ca0a194", "name"=>"全局管綜視點"}, {"id"=>"7a1baa69-baab-434f-bcf0-aa885ab07ed4", "name"=>"管綜細部"}, {"id"=>"441d05a2-bcc6-4e19-8eb7-f239934f395c", "name"=>"空調機組"}, {"id"=>"1b35039c-906d-409f-98c7-5affd2fd2ef3", "name"=>"水泵"}, {"id"=>"c4f99f19-dc28-4b52-b00c-007e59ea35b7", "name"=>"透視1"}, {"id"=>"ed04969b-dabb-4575-bc10-f09104ab8f67", "name"=>" 透視2"}]
irb(main):022:0> arr.length
=> 6
irb(main):023:0> arr[0].name
NoMethodError: undefined method `name' for #<Hash:0x00000003c58db8>
from (irb):23
from /usr/lib/ruby/vendor_ruby/rails/commands/console.rb:47:in `start'
from /usr/lib/ruby/vendor_ruby/rails/commands/console.rb:8:in `start'
from /usr/lib/ruby/vendor_ruby/rails/commands.rb:41:in `<top (required)>'
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from script/rails:6:in `<main>'
irb(main):024:0> arr[0][name]
NameError: undefined local variable or method `name' for main:Object
from (irb):24
from /usr/lib/ruby/vendor_ruby/rails/commands/console.rb:47:in `start'
from /usr/lib/ruby/vendor_ruby/rails/commands/console.rb:8:in `start'
from /usr/lib/ruby/vendor_ruby/rails/commands.rb:41:in `<top (required)>'
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from script/rails:6:in `<main>'
irb(main):025:0> arr[0]
=> {"id"=>"260e053b-d728-4785-888d-eb4f1ca0a194", "name"=>"全局管綜視點"}
irb(main):026:0> vp1=arr[0]
=> {"id"=>"260e053b-d728-4785-888d-eb4f1ca0a194", "name"=>"全局管綜視點"}
irb(main):027:0> vp1.id
NoMethodError: undefined method `id' for #<Hash:0x00000003c58db8>
from (irb):27
from /usr/lib/ruby/vendor_ruby/rails/commands/console.rb:47:in `start'
from /usr/lib/ruby/vendor_ruby/rails/commands/console.rb:8:in `start'
from /usr/lib/ruby/vendor_ruby/rails/commands.rb:41:in `<top (required)>'
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from script/rails:6:in `<main>'
irb(main):028:0> vp1["id"]
=> "260e053b-d728-4785-888d-eb4f1ca0a194"
irb(main):029:0> vp1[:id]
=> nil
只要一句命令就可以將JSON解析為ruby對象(array、hash)。
把博客用起來,記錄一下自己填過的坑。
文章列表
留言列表