首页 > 解决方案 > 在 Ruby 中从具有嵌套 JSON 键值对的类创建新实例/对象

问题描述

我有一些想要转换为对象的 JSON,但我无法弄清楚如何对数据进行排序并将其传递给类的初始化方法。

我已经使用 file.read 将我的 JSON 放入数组中组织的键/值对中,但是成本属性嵌套如下

      [
        { "restaurant": "hells kitchen", "cost": { "dine in": 100.00 } },
        { "restaurant": "sals pizza", "cost": { "dine in": 25.50, "takeaway": 20.00, "delivery": 28.50 } },
        { "restaurant": "five guys burgers", "cost": { "dine in": 18.50, "takeaway": 16.50, "delivery": 20.00 } }
      ]

理想情况下,我想分配这些值并将它们作为实例化类对象的属性进行访问,就像这样一个粗略的例子。

class Restaurant

    attr_accessor :name, :type, :cost

    def initialise(json_data)
    
    #something to sort the data here#
    
    end

end 

我想不出将数据添加到属性的好方法,并且非常感谢有关如何检索数据并将其放入初始化方法的任何建议。

如果我缺乏术语、解释或理解,我提前道歉,我对 Ruby 和一般编程非常陌生。

谢谢!

标签: jsonrubysortinginitializationnested-lists

解决方案


json 是一个哈希数组。

abc = [
        { "restaurant": "hells kitchen", "cost": { "dine in": 100.00 } },
        { "restaurant": "sals pizza", "cost": { "dine in": 25.50, "takeaway": 20.00, "delivery": 28.50 } },
        { "restaurant": "five guys burgers", "cost": { "dine in": 18.50, "takeaway": 16.50, "delivery": 20.00 } }
      ]

irb(main):008:0> abc
=> [{:restaurant=>"hells kitchen", :cost=>{:"dine in"=>100.0}}, {:restaurant=>"sals pizza", :cost=>{:"dine in"=>25.5, :takeaway=>20.0, :delivery=>28.5}}, {:restaurant=>"five guys burgers", :cost=>{:"dine in"=>18.5, :takeaway=>16.5, :delivery=>20.0}}]

因此,您可以直接操纵它

irb(main):009:0> abc[0]
=> {:restaurant=>"hells kitchen", :cost=>{:"dine in"=>100.0}}

我不知道你到底想做什么,但所有数组方法都可以直接使用: map, each,...

在初始化方法中,您可以操作数据并设置您的类变量和方法变量。attr_reader如果在初始化方法中设置变量就足够了。


推荐阅读