ハッシュの値をアクセサで呼べるようにする
実現方法
HashをStructに変換します
変換コード
def self.hash_to_struct(hash) vals = *hash.values.map do |val| case val when Array val.map do |array_val| if array_val.is_a?(Hash) hash_to_struct(array_val) else array_val end end when Hash hash_to_struct(val) else val end end Struct.new(*hash.symbolize_keys.keys).new(*vals) end
使い方
json = <<-EOS { "entry" : [ { "name" : "ほげタロウ", "age" : "30" }, { "name" : "ほげ子", "age" : "31" } ], "startIndex" : 1, "itemsPerPage" : 50, "totalResults" : 2 } EOS hash = JSON.parse(json) obj = hash_to_struct(hash) puts obj.startIndex puts obj.itemsPerPage obj.entry.each do |val| puts val.name puts val.age end
実行環境
ruby (1.9.2)