【问题标题】:Iterate JSON file into Ruby object array将 JSON 文件迭代到 Ruby 对象数组中
【发布时间】:2017-02-13 18:55:55
【问题描述】:

实现以下目标的最佳方法是什么?:

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

JSON 文件:

[{"id":"1","name":"Some Name","email":"something@gmail.com"},
 {"id":"2","name":"Another Name","email":"another@gmail.com"}]

现在我想读取 JSON 文件,将其解析为对象数组 Whatever,以便 array[0] 有一个带有第一个 json 对象的 Whatever 类对象,array[1] 将有一个 Whatever类对象与第二个 json 对象。

在 ruby​​ 中实现这一目标的最佳方法是什么?

【问题讨论】:

  • 旁注: 在 ruby​​ 中,您应该以大写字母开头命名类。此外,您必须展示您已经尝试过的内容。

标签: arrays json ruby parsing


【解决方案1】:

如果这就是你的课程,那就没有那么漂亮了:

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)

【讨论】:

  • 在这种情况下不要忘记OpenStruct
  • 在你的第一个例子中,我假设数组是'whatevers'?在 JSON.parse 中。
  • @GregBrethen,whatevers 是一个字符串,包含您问题中描述的 json。又名'[{"id":"1","name":"Some Name","email":"something@gmail.com"}, {"id":"2","name":"Another Name","email":"another@gmail.com"}]'
  • 那么我需要将“元素”泵入一个数组吗?
  • @GregBrethen,不确定您所说的 pump 是什么意思。 JSON.parse 将开始迭代字符串中的 json 数组,并且对于 json 数组中的每个元素,它将并列一个 Whatever 对象。 Aka 你最终只想将解析的结果分配给一个变量,它将包含解析的数组。又名result = JSON.parse(whatevers).map do |whatever| ....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多