Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How can I convert an array of data to hash and to json format?

Tags:

ruby

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?

like image 851
TheOneTeam Avatar asked May 31 '12 07:05

TheOneTeam


1 Answers

array.map { |o| Hash[o.each_pair.to_a] }.to_json
like image 162
Nick Colgan Avatar answered Oct 19 '22 13:10

Nick Colgan