0

我有一个来自 URL 的 XML 响应,该响应被转换为一个哈希数组,如下所示:

{
  “员工名单”=>{
    “员工档案”=>{
      "BuildLoc"=>{"$"=>"1 个快乐的地方"},
      "状态"=>{"$"=>"A"},
      "SecrTitle"=>[{}, {}],
      “ID”=>{},
      “bct”=>{},
      "NUM"=>{"$"=>"1234567"},
      "BuildCity"=>{"$"=>"代顿"},
      "BuildFloor"=>{"$"=>"6"},
      "费用"=>{"$"=>"1345"},
      "姓氏"=>{"$"=>"史密斯"},
      “中”=>{},
      "SecrName"=>[{}, {}],
      "内部SMTP地址"=>{"$"=>"Joe.Smith@happy.com"},
      "IAddress"=>{"$"=>"Joe.Smith@happy.com"},
      "PreferredLastName"=>{},
      "DisplayName"=>{"$"=>"Joe Smith"},
      "CellPhoneNo"=>{},
      "职称"=>{"$"=>"博士"},
      "BuildStreetAddress"=>{"$"=>"123 欢乐小镇"},
      "BuildState"=>{"$"=>"IL"},
      "名字"=>{"$"=>"乔"},
      "AltContactTitle1"=>{},
      "部门成本CtrNo"=>{"$"=>"129923"},
      "PreferredFirstName"=>{"$"=>"乔"},
      "AltContactName2"=>{},
      "AltContactPhone2"=>{},
      "GDP"=>{},
      "BuildZip"=>{"$"=>"112345"},
      "RegionID"=>{"$"=>"NAMR"},
      "就业类型"=>{"$"=>"E"},
      "临时电话"=>{},
      "BuildID"=>{"$"=>"01114"},
      "CountryAbbr"=>{"$"=>"USA"},
      "FaxDisp1"=>{},
      "BuildCountry"=>{"$"=>"United States"}
    }
  },
  无=>无
}

提取“ DisplayName”和“ InternalSMTPAddress”值的最简单方法是什么?

4

3 回答 3

1

如果将返回的哈希分配给名为“ hash”的变量,则可以访问这些键的两个所需值,例如:

hash['EmployeeList']['EmployeeProfile']['DisplayName']
=> {"$"=>"Joe Smith"}

hash['EmployeeList']['EmployeeProfile']['InternalSMTPAddress']
=> {"$"=>"Joe.Smith@happy.com"}

如果您想要其中的实际数据,请添加尾随['$']

hash['EmployeeList']['EmployeeProfile']['DisplayName']['$']
=> "Joe Smith"

hash['EmployeeList']['EmployeeProfile']['InternalSMTPAddress']['$']
=> "Joe.Smith@happy.com"
于 2012-07-25T21:36:57.253 回答
0

如果您需要在嵌套哈希中找到一些键,请使用此方法:

def find_key(hash,key)
  hash.each {|k, v|
    return v if k==key
    tmp=find_key(v,key) if v.is_a?(Hash)
    return tmp unless tmp.nil?
  }
  return nil
end

用法:

hash = Hash.new
hash["key1"] = "value1"
hash["key2"] = "value2"
hash["key3"] = Hash.new
hash["key3"]["key4"] = "value4"
hash["key3"]["key5"] = "value5"
hash["key6"] = Hash.new
hash["key6"]["key7"] = "value7"
hash["key6"]["key8"] = Hash.new
hash["key6"]["key8"]["key9"] = "value9"

find_key(hash,"key9") => "value9"
find_key(hash,"key8") => {"key9"=>"value9"}
find_key(hash,"dsfsdfsd") => nil
于 2012-07-25T21:50:42.027 回答
0

我建议您使用 ruby​​ gem nested_lookup

使用命令安装 gemgem install nested_lookup

在您的情况下,您需要“DisplayName”和“InternalSMTPAddress”的值。这是你需要做的。

Rameshs-MacBook-Pro:~ rameshrv$ irb
irb(main):001:0> require 'nested_lookup'
=> true
irb(main):051:0> include NestedLookup
=> Object
# Here the test_data is the data you gave in the question
irb(main):052:0> test_data.nested_get('DisplayName')
=> {"$"=>"Joe Smith"}
irb(main):053:0> test_data.nested_get('InternalSMTPAddress')
=> {"$"=>"Joe.Smith@happy.com"}
irb(main):054:0>

有关更多信息,请阅读https://github.com/rameshrvr/nested_lookup

于 2018-11-19T14:00:54.357 回答