ruby-on-rails - ruby 中的破解如何访问转换为哈希的 JSON 中的数据?

标签 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"] 显示了所有值,但我尝试了 array["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}

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

最佳答案

像这样?

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 指向的数组。

关于ruby-on-rails - ruby 中的破解如何访问转换为哈希的 JSON 中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4531322/

相关文章:

jquery - 在 Rails 中,如何从 Jquery 中将参数传递给 Controller ​​方法,然后获取返回值?

java - 将字符串String对象转换为可迭代的json对象

ruby-on-rails - 如何为 Rails 上的 Stripe 结账编写集成测试?

jquery - 在悬停时替换 Ruby 链接文本

ruby-on-rails - 如何测试我的 Controller 是否在 Rails 3 上呈现了正确的布局?

ruby - 从数组中删除一个

ruby - 查找最接近数组平均值的元素

c - 为什么我不能填充并返回我用 rb_ary_new 创建的数组?

javascript - 使用 javascript 解析 JSON

javascript - 无法为 Javascript 中的对象分配新值