如何获得密钥=>这个foursquare哈希的价值?

时间:2010-09-03 14:51:25

标签: ruby arrays hash

这是它的样子:

{
  "groups" => [
    { "venues" => [
      { "city"     => "Madrid",
        "address"  => "Camino de Perales, s/n",
        "name"     => "Caja Mágica",
        "stats"    => {"herenow"=>"0"},
        "geolong"  => -3.6894333,
        "primarycategory" => {
          "iconurl"      => "http://foursquare.com/img/categories/arts_entertainment/stadium.png",
          "fullpathname" => "Arts & Entertainment:Stadium",
          "nodename"     => "Stadium",
          "id"           => 78989 },
        "geolat"   => 40.375045,
        "id"       => 2492239,
        "distance" => 0,
        "state"    => "Spain" }],
      "type"   => "Matching Places"}]
}

大而丑......我只是想抓住这个id。我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

h = {“groups”=> .........}

两个ID是:

h["groups"][0]["venues"][0]["primarycategory"]["id"]
h["groups"][0]["venues"][0]["id"]

答案 1 :(得分:0)

如果哈希存储一个id :(假设该值存储在名为hash的变量中)

hash["groups"][0]["venues"][0]["primarycategory"]["id"] rescue nil

如果哈希存储了多个ID,那么:

ids = Array(hash["groups"]).map do |g|
  Array(g["venues"]).map do |v|
    v["primarycategory"]["id"] rescue nil
  end.compact
end.flatten

ids包含id的数组。