By default, a Struct instance will be displayed as a string when json is encoded using json ruby gem:
require 'json' array = [#<struct id=1, car='red'>, #<struct id=2, car='yellow'>, #<struct id=3, car='green'>] # assuming real structure code in the array puts array.to_json
prints
["#<struct id=1, car='red'>", "#<struct id=2, car='yellow'>", "#<struct id=3, car='green'>"]
This is clearly not what you want.
The next logical step is to make sure that your instances of the structure can be correctly serialized in JSON and also created from JSON.
To do this, you can change the declaration of your structure:
YourStruct = Struct.new(:id, :car) class YourStruct def to_json(*a) {:id => self.id, :car => self.car}.to_json(*a) end def self.json_create(o) new(o['id'], o['car']) end end
So now you can write the following:
a = [ YourStruct.new(1, 'toy'), YourStruct.new(2, 'test')] puts a.to_json
which prints
[{"id": 1,"car":"toy"},{"id": 2,"car":"test"}]
and also deserialize from JSON:
YourStruct.json_create(JSON.parse('{"id": 1,"car":"toy"}')) # => #<struct YourStruct id=1, car="toy">