如何通过ruby中的破解访问JSON中转换为哈希的数据?

时间:2010-12-25 19:10:50

标签: ruby-on-rails ruby json hash

以下是破解文档中的示例:

json = '{"posts":[{"title":"Foobar"}, {"title":"Another"}]}'
Crack::JSON.parse(json)
=> {"posts"=>[{"title"=>"Foobar"}, {"title"=>"Another"}]}

但是我如何实际访问哈希中的数据?

我尝试了以下内容:

array = Crack::JSON.parse(json)
array["posts"]

array [“posts”]显示所有值,但我尝试了数组[“posts”] [“title”]但它没有用。

以下是我要解析的内容:

{"companies"=>[{"city"=>"San Mateo", "name"=>"Jigsaw", "address"=>"777 Mariners Island Blvd Ste 400", "zip"=>"94404-5059", "country"=>"USA", "companyId"=>4427170, "activeContacts"=>168, "graveyarded"=>false, "state"=>"CA"}], "totalHits"=>1}

我想访问公司下的各个元素....比如城市和名字。

1 个答案:

答案 0 :(得分:7)

喜欢这个吗?

hash = {
  "companies" => [
    {
      "city"           => "San Mateo", 
      "name"           => "Jigsaw", 
      "address"        => "777 Mariners Island Blvd Ste 400", 
      "zip"            => "94404-5059", 
      "country"        => "USA", 
      "companyId"      => 4427170, 
      "activeContacts" => 168, 
      "graveyarded"    => false, 
      "state"          => "CA"
    }
  ], 
  "totalHits" => 1
}

hash['companies'].each{ |i| 
  puts "city => #{i['city']}"
  puts "name => #{i['name']}" 
}
# >> city => San Mateo
# >> name => Jigsaw

hash['companies'][0]['city'] # => "San Mateo"
hash['companies'][0]['name'] # => "Jigsaw"

问题是您没有考虑companies指向的数组。