简体   繁体   中英

Ruby - How to parse string to array of hashes

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?

That format is called JavaScript Object Notation (JSON) and can be parsed by a 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM