![](/img/trans.png)
[英]Ruby - How can i convert a Hash to Json array without “[” turning into ''{“0”:"
[英]Ruby: How can I convert an array of data to hash and to json format?
我是Ruby数组和哈希操作的新手。
我该怎么做这个简单的转换?
array = [#<struct id=1, car='red'>, #<struct id=2, car='yellow'>, #<struct id=3, car='green'>]
json中所需的输出:
[{id : 1, car : 'red'} , {id:2, car :'yellow'} ,{id:3 , car: "green"}]
有人有任何提示吗?
array.map { |o| Hash[o.each_pair.to_a] }.to_json
将struct
对象的数组转换为hash
数组,然后调用to_json
。 您需要使用json
(ruby 1.9)才能使用to_json
方法。
array.collect { |item| {:id => item.id, :car => item.car} }.to_json
默认情况下,使用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
版画
["#<struct id=1, car='red'>", "#<struct id=2, car='yellow'>", "#<struct id=3, car='green'>"]
这显然不是你想要的。
下一个逻辑步骤是确保您的结构实例可以正确地序列化为JSON,以及从JSON创建。
为此,您可以更改结构的声明:
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
所以你现在可以写下面的内容:
a = [ YourStruct.new(1, 'toy'), YourStruct.new(2, 'test')]
puts a.to_json
打印
[{"id": 1,"car":"toy"},{"id": 2,"car":"test"}]
并且还从JSON反序列化:
YourStruct.json_create(JSON.parse('{"id": 1,"car":"toy"}'))
# => #<struct YourStruct id=1, car="toy">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.