10

I am very new to Ruby array and hash manipulation.

How can I do this simple transformation?

array = [#<struct id=1, car='red'>, #<struct id=2, car='yellow'>, #<struct id=3, car='green'>]

desired output in json:

[{id : 1, car : 'red'} , {id:2, car :'yellow'} ,{id:3 , car: "green"}]

Does anyone have any hints?

1
  • 3
    the desired output is not valid json. You mean an array? [...] Commented May 31, 2012 at 8:02

3 Answers 3

16
array.map { |o| Hash[o.each_pair.to_a] }.to_json
Sign up to request clarification or add additional context in comments.

2 Comments

You must require 'json' to get the to_json function.
You can also write .to_h instead.
7

Convert array of struct objects into array of hash, then call to_json. You need to require json (ruby 1.9) in order to use the to_json method.

array.collect { |item| {:id => item.id, :car => item.car} }.to_json

Comments

2

By default a Struct instance will be displayed as a string when encoding to json using the 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 obviously not what you want.

The next logical step is to make sure that your struct instances can be properly serialized to JSON, as well as created back from JSON.

To do this you can alter 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 you can now 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">

1 Comment

very grateful for this. i tried many other solutions and this was the first that worked... maybe someday I'll actually understand it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.