迭代JSON文件到Ruby对象数组

问题描述:

什么是实现以下?:迭代JSON文件到Ruby对象数组

class Whatever 
    attr_accessor :id, :name, :email 
end 

JSON文件的最好方法:

[{"id":"1","name":"Some Name","email":"[email protected]"}, 
{"id":"2","name":"Another Name","email":"[email protected]"}] 

现在我想读JSON文件中,解析它成对象Whatever的阵列,使得array[0]具有与第一JSON对象Whatever类对象和array[1]将具有与第二JSON对象Whatever类对象。

什么是Ruby来实现这一目标的最佳方式是什么?

+2

_Sidenote:_在红宝石你应该不适用我以大写字母开头的课程。另外,你必须展示你已经尝试过的东西。 – mudasobwa

没有一个所有漂亮的方式,如果这是你对类:

JSON.parse(whatevers).map do |whatever| 
    element = Whatever.new 
    element.id = whatever['id'] 
    element.name = whatever['name'] 
    element.email = whatever['email'] 
    element 
end 

但是,如果添加索引方法,如:

class Whatever 
    def []=(name, value) 
    instance_variable_set("@#{name}", value) 
    end 
end 

它取决于:

JSON.parse(whatevers, object_class: Whatever) 
+1

不要忘记[OpenStruct(https://ruby-doc.org/stdlib-2.4.0/libdoc/ostruct/rdoc/OpenStruct.html)像这样的情况。 – tadman

+0

在你的第一个例子中,我假设这个数组是'whatevers'?在JSON.parse中。 –

+0

@GregBrethen,'whatevers'是一个字符串,持有你的问题中描述的json。又名''[{ “ID”: “1”, “名”: “有些名称”, “电子邮件”: “[email protected]”},{ “ID”: “2”, “名”:“另一个名称”,‘电子邮件’:‘[email protected]’}]'' – ndn