Ruby: How to convert data array to hash and json format?

I am very new to working with Ruby array and hash manipulation.

How can I do this simple conversion?

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?

+6
source share
3 answers
 array.map { |o| Hash[o.each_pair.to_a] }.to_json 
+14
source

Convert an array of struct objects into a hash array, then call to_json . To use the to_json method to_json you need json (ruby 1.9).

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

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"> 
+2
source

Source: https://habr.com/ru/post/917077/


All Articles