我必须模仿Google API响应,并创建一个由.
遍历的2级深数据结构:
=> user.names.first_name
鲍勃
有比这更聪明/更好的方法:
user = OpenStruct.new(names: OpenStruct.new(first_name: 'Bob'))
此方法是粗鲁的方法,但有效,
require 'ostruct'
require 'json'
# Data in hash
data = {"names" => {"first_name" => "Bob"}}
result = JSON.parse(data.to_json, object_class: OpenStruct)
另一种方法是将方法添加到哈希类本身中,
class Hash
def to_openstruct
JSON.parse to_json, object_class: OpenStruct
end
end
使用上述方法您可以将哈希转换为openscruct
data = {"names" => {"first_name" => "Bob"}}
data.to_openstruct