json - 在 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 和一般编程非常陌生。
谢谢!
解决方案
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
如果在初始化方法中设置变量就足够了。
推荐阅读
- sympy - 评估 sympy 函数的解对
- python - Python 上的图形 plt.plot 不会显示
- javascript - 无法读取未定义的 javascript 数组的属性“长度”
- java - 如何让 Avro SchemaBuilder 在两个“记录”之间构建映射模式?
- php - 在 PHP 中调用扩展可变参数函数的父方法?
- c# - 如何将 txt azure blobs 下载为纯文本文件?
- python - 匹配具有相似列的两个数据框
- php - 如何使用通配符来允许特定域 CORS?
- dependent-type - 在依赖类型的编程语言中,Type-in-Type 是否适用于编程?
- node.js - Puppeteer 在 Node 10 运行时中无法使用谷歌云功能