ruby - How to generate direct access keys to nested hash which contains hash and arrays as values? -
i want compare 2 xml files 1 input , other output. converting both hash.
my idea keys input xml converted hash, , search each key in both input , output hashes respective key/value pairs.
i have hash:
{ "requisition_header" => { "requested_by" => {"login" => "coupasupport"}, "department" => {"name" => "marketing"}, "ship_to_address" => {"name" => "address_1431693296"}, "justification" => nil, "attachments" => [], "requisition_lines" => [ { "description" => "cleaning services building a", "line_num" => 1, "need_by_date" => 2010-09-23 07:00:00 utc, "source_part_num" => nil, "supp_aux_part_num" => nil, "unit_price" => #<bigdecimal:a60520c,'0.3e4',9(18)>, "supplier" => {"name" => "amazon.com"}, "account" => { "code" => "sf-marketing-indirect", "account_type" => {"name" => "ace corporate"} }, "currency" => {"code" => "usd"}, "payment_term" => {"code" => "net 30"}, "shipping_term" => {"code" => "standard"}, "commodity" => {"name" => "marketing-services"} } ] } }
it nested , values not directly accessible.
i want way generate direct access each value in hash.
for example:
requisition_header.requested_by.login
will access "coupasupport".
requisition_header.department.name
will access "marketing".
requisition_header.requisition_lines[0].description
will access "cleaning services building a".
requisition_header.requisition_lines[0].line_num
will access "1".
requisition_header.requisition_lines[0].need_by_date
will access "2010-09-23 07:00:00 utc".
each key built can used search value directly inside hash.
that done following method, translates nested hash nested openstruct
s:
require 'ostruct' def deep_structify(hash) result = {} hash.each |key, value| result[key] = value.is_a?(hash) ? deep_structify(value) : value end if hash openstruct.new(result) end hash = {"requisition_header"=>{"requested_by"=>{"login"=>"coupasupport"}, "department"=>{"name"=>"marketing"}, "ship_to_address"=>{"name"=>"address_1431693296"}, "justification"=>nil, "attachments"=>[], "requisition_lines"=>[{"description"=>"cleaning services building a", "line_num"=>1, "need_by_date"=>2010-09-23 07:00:00 utc, "source_part_num"=>nil, "supp_aux_part_num"=>nil, "unit_price"=>#<bigdecimal:a60520c,'0.3e4',9(18)>, "supplier"=>{"name"=>"amazon.com"}, "account"=>{"code"=>"sf-marketing-indirect", "account_type"=>{"name"=>"ace corporate"}}, "currency"=>{"code"=>"usd"}, "payment_term"=>{"code"=>"net 30"}, "shipping_term"=>{"code"=>"standard"}, "commodity"=>{"name"=>"marketing-services"}}]}} struct = deep_structify(hash) struct.requisition_header.department.name #=> "marketing"
Comments
Post a Comment