简体   繁体   English

Ruby:如何将数据数组转换为hash和json格式?

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

I am very new to Ruby array and hash manipulation. 我是Ruby数组和哈希操作的新手。

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: json中所需的输出:

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

Does anyone have any hints? 有人有任何提示吗?

array.map { |o| Hash[o.each_pair.to_a] }.to_json

Convert array of struct objects into array of hash , then call to_json . struct对象的数组转换为hash数组,然后调用to_json You need to require json (ruby 1.9) in order to use the to_json method. 您需要使用json (ruby 1.9)才能使用to_json方法。

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

By default a Struct instance will be displayed as a string when encoding to json using the json ruby gem: 默认情况下,使用json ruby​​ gem编码为json时,Struct实例将显示为字符串:

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. 下一个逻辑步骤是确保您的结构实例可以正确地序列化为JSON,以及从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: 并且还从JSON反序列化:

YourStruct.json_create(JSON.parse('{"id": 1,"car":"toy"}'))
# => #<struct YourStruct id=1, car="toy">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM