Ruby - 如何将字符串解析为哈希数组

时间:2014-06-03 15:13:11

标签: ruby arrays hash

我有一个存储在数据库中的字符串,如下所示:

images = '[{"id":1,"type":"Image","image_id":"asdf123"},{"id":2,"type":"Image","image_id":"asdf456"},{"id":3,"type":"Image","image_id":"asdf890"}]'

并希望将其转换为数组,以便我可以执行以下操作:

images.each do |image|
    puts image.image_id
end

这真的只是删除外方括号,然后按照此问题Converting a Ruby String into an array中的步骤进行,还是有更直接/更优雅的方法?

1 个答案:

答案 0 :(得分:8)

该格式称为JavaScript Object Notation (JSON),可以由builtin Ruby library解析:

require 'json'

images_str = '[{"id":1,"type":"Image","image_id":"asdf123"},{"id":2,"type":"Image","image_id":"asdf456"},{"id":3,"type":"Image","image_id":"asdf890"}]'

images = JSON.parse(images_str)
images.size           # => 3
images[0].class       # => Hash
images[0]['image_id'] # => "asdf123"

images.each { |x| puts "#{x['id']}: #{x['image_id']}" }
# 1: asdf123
# 2: asdf456
# 3: asdf890