Ruby——如何将字符串解析为散列数组

时间:2021-05-10 16:01:34

I have a string stored in a database like so:

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

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

And would like to convert it to an array so I can do something like:

我想把它转换成一个数组我可以这样做:

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

Is it really just a matter of removing the outer square brackets and then following the procedure from this question Converting a Ruby String into an array or is there a more direct/elegant method?

这真的只是删除外方括号,然后按照问题中的步骤将Ruby字符串转换为数组吗?还是有更直接/更优雅的方法?

1 个解决方案

#1


7  

That format is called JavaScript Object Notation (JSON) and can be parsed by a builtin Ruby library:

这种格式被称为JavaScript对象表示法(JSON),可以通过构建的Ruby库进行解析:

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

#1


7  

That format is called JavaScript Object Notation (JSON) and can be parsed by a builtin Ruby library:

这种格式被称为JavaScript对象表示法(JSON),可以通过构建的Ruby库进行解析:

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