4

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?

Community
  • 1
  • 1
waffl
  • 5,179
  • 10
  • 73
  • 123
  • Question is not clear. What is the format in which the database is stored? It is not a matter of removing the outer square brackets. – sawa Jun 03 '14 at 15:20
  • @sawa Why isn't it clear? The question states "I have a string stored in a database", it is stored as a string. – waffl Jun 03 '14 at 15:22
  • FYI, there is more than one format of database in the world. Also, what you gave is not a valid Ruby string. – sawa Jun 03 '14 at 15:32

1 Answers1

8

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
maerics
  • 151,642
  • 46
  • 269
  • 291
  • Thank you, that's what I thought, I've been trying to loop through the results of `JSON.parse` with `images.each do |image|` but keep getting `undefined method 'each' for nil:NilClass` am I going about this the wrong way? – waffl Jun 03 '14 at 15:22
  • 1
    @waffl: without seeing your exact code and data it's hard to say why you might see that error; however, my guess is that you are not actually parsing the JSON string you expect so you get a nil value instead of an array. – maerics Jun 03 '14 at 15:25
  • you are correct – I was not parsing the correct string, and this works perfectly! – waffl Jun 03 '14 at 15:35