Ruby fetch api多维哈希过滤器

时间:2017-11-04 04:02:39

标签: ruby

我是新人。我需要从此哈希中检索特定的人员信息。说我想得到Micheal Jordans的信息(以粗体显示)。我有这段代码:

jdoc.fetch("schedule").fetch("schedule_layers").fetch(users).each do |jsonUser|
puts jsonUser
end

但它似乎不起作用。我认为它会给出“用户”键的所有值,但它只是吐出了整个事情。我如何通过代码获取Micheal Jordan的信息?

非常感谢!请帮助我理解!

"schedule_layers"=>
    [{"name"=>"Layer 1",
      "rendered_schedule_entries"=>[],
      "rendered_coverage_percentage"=>nil,
      "id"=>”A1B2C3”,
      "start"=>"2017-10-09:00:46-05:00",
      "end"=>nil,
      "rotation__start"=>"2017-10-02T20:30:00-05:00",
      "length_seconds"=>36000, 
      "users"=>
        {"user"=>
          {"id"=>”0000001”,
           "type"=>"user_reference”,
           "summary"=>”Larry.Bird”,
           "self"=>"https://api.com/users/0000001”,
           "html_url"=>"https://target.com/users/0000001”}}],
      "restrictions"=>
       [{"type"=>"daily_restriction",
         "start_time_of_day"=>”00:30:00",
         "duration_seconds"=>120000}]},
     {"name"=>"Layer 2",
      "schedule_entries"=>[],
      "coverage_percentage"=>nil,
      "id"=>”0000002”,
      "start"=>"2016-12-18:00:51-55:00",
      "end"=>”2017–05-18:12:51-55:00",
      "virtual_start"=>"2016-20-17:00:10-05:00",
      "turn_length_seconds"=>120000,
      "users"=>
        {"user"=>
          **{"id"=>”0000003”,
           "type"=>"user_reference",
           "summary"=>”Micheal.Jordan”,
           "self"=>"https://api.com/users/0000003”,
           "html_url"=>"https://target.com/users/0000003”}},**
        {"user"=>
          {"id"=>”0000004”,
           "type"=>"user_reference",
           "summary"=>”Allen.Iverson”,
           "self"=>"https://api.com/users/0000004”,
           "html_url"=>"https://target.com/users/0000004”}},
           "restrictions"=>[]},

1 个答案:

答案 0 :(得分:0)

您似乎在fetch(users)中使用了错误的语法。

我想你需要做这样的事情(我使用符号代替字符串):

json_hash = {
  schedule_layers: [
    {
       name: 'l1',
       users: [
         { name: 'u1' },
         { name: 'u2' }
       ]
    },
    {
       name: 'l2',
       users: [
         { name: 'u3' }
       ]
    }
  ]
}

[2] pry(main)> json_hash.fetch(:schedule_layers).flat_map {|x| x[:users] }.each {|x| p x }
{:name=>"u1"}
{:name=>"u2"}
{:name=>"u3"}
=> [{:name=>"u1"}, {:name=>"u2"}, {:name=>"u3"}]

要选择特定用户,您可以使用select方法:

[3] pry(main)> json_hash.fetch(:schedule_layers).flat_map {|x| x[:users] }.select {|x| x[:name] == 'u3' }
=> [{:name=>"u3"}]