今天遇到了一个要解析JSON的需求。在http://*.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)。
把博客用起来,记录一下自己填过的坑。