Ruby:基于多个条件从深层嵌套的JSON结构中提取

时间:2016-11-20 19:20:06

标签: json ruby hash

我想选择marketId marketName == 'Moneyline' countryCode == 'US' || 'GB',但只选eventName.include?(' @ ')space。 (@之前和之后的countryCode)。我尝试了不同的地图和选择组合,但是有些节点没有{"currencyCode"=>"GBP", "eventTypes"=>[ {"eventTypeId"=>7522, "eventNodes"=>[ {"eventId"=>28024331, "event"=> {"eventName"=>"EWE Baskets Oldenburg v PAOK Thessaloniki BC" }, "marketNodes"=>[ {"marketId"=>"1.128376755", "description"=> {"marketName"=>"Moneyline"} }, {"marketId"=>"1.128377853", "description"=> {"marketName"=>"Start Lublin +7.5"} }}}]}, {"eventId"=>28023434, "event"=> {"eventName"=>"Asseco Gdynia v Start Lublin", "countryCode"=>"PL", }, "marketNodes"=> [{"marketId"=>"1.128377853", ETC... 这让我感到困惑。 This是源代码,但它可能是一个示例:

#generate data
library(xts)
library(dygraphs)

#generate sample data
#http://stackoverflow.com/questions/9778632/r-xts-generating-1-minute-time-series-from-second-events
x <- xts(cumsum(rnorm(400000, 0, 0.2)), Sys.time() - 400000:1)
x <- to.minutes(x)

#display dygraph
dygraph(x) %>%
  dyCandlestick() %>%
  dyRangeSelector(height=20)

1 个答案:

答案 0 :(得分:2)

基于之前的answer,您只需要在eventNodes上添加一个select:

require 'json'

json = File.read('data.json')
hash = JSON.parse(json)

moneyline_market_ids = hash["eventTypes"].map{|type|
  type["eventNodes"].select{|event_node|
    ['US', 'GB'].include?(event_node["event"]["countryCode"]) || event_node["event"]["eventName"].include?(' @ ')
  }.map{|event|
    event["marketNodes"].select{|market|
      market["description"]["marketName"] == 'Moneyline'
    }.map{|market|
      market["marketId"]
    }
  }
}.flatten

puts moneyline_market_ids.join(', ')
#=> 1.128255531, 1.128272164, 1.128255516, 1.128272159, 1.128278718, 1.128272176, 1.128272174, 1.128272169, 1.128272148, 1.128272146, 1.128255464, 1.128255448, 1.128272157, 1.128272155, 1.128255499, 1.128272153, 1.128255484, 1.128272150, 1.128255748, 1.128272185, 1.128278720, 1.128272183, 1.128272178, 1.128255729, 1.128360712, 1.128255371, 1.128255433, 1.128255418, 1.128255403, 1.128255387

如果您想使用ID:

保留国家/地区代码和名称信息
moneyline_market_ids = hash["eventTypes"].map{|type|
  type["eventNodes"].map{|event_node|
    [event_node, event_node["event"]["countryCode"], event_node["event"]["eventName"]]
  }.select{|_, country, event_name|
    ['US', 'GB'].include?(country) || event_name.include?(' @ ')
  }.map{|event, country, event_name|
    event["marketNodes"].select{|market|
      market["description"]["marketName"] == 'Moneyline'
    }.map{|market|
      [market["marketId"],country,event_name]
    }
  }
}.flatten(2)

require 'pp'
pp moneyline_market_ids
#=> [["1.128255531", "US", "Philadelphia @ Seattle"],
#   ["1.128272164", "US", "Arkansas @ Mississippi State"],
#   ["1.128255516", "US", "New England @ San Francisco"],
#   ["1.128272159", "US", "Indiana @ Michigan"],
#   ["1.128278718", "CA", "Edmonton @ Ottawa"],
#   ["1.128272176", "US", "Arizona State @ Washington"],
#   ["1.128272174", "US", "Alabama A&M @ Auburn"],
#    ...