给定一个json对象,如何遍历rails中的对象

时间:2011-08-04 03:34:22

标签: ruby-on-rails ruby json ruby-on-rails-3

我的应用将以下json对象发布到rails。

[{\"completed\":false,\"id\":196,\"position\":0,\"title\":\"Item 1\",\"updated_at\":\"2011-08-03T21:17:09Z\"},{\"completed\":false,\"id\":193,\"position\":1,\"title\":\"Item X\",\"updated_at\":\"2011-08-03T21:16:19Z\"},{\"completed\":false,\"id\":197,\"position\":2,\"title\":\"Item 2\",\"updated_at\":\"2011-08-03T21:17:11Z\"},{\"completed\":false,\"id\":192,\"position\":3,\"title\":\"Item Z\",\"updated_at\":\"2011-08-03T21:16:17Z\"},{\"completed\":false,\"id\":194,\"position\":4,\"title\":\"Item Y\",\"updated_at\":\"2011-08-03T21:16:21Z\"},{\"completed\":false,\"id\":195,\"position\":5,\"title\":\"Item P\",\"updated_at\":\"2011-08-03T21:16:25Z\"},{\"completed\":false,\"id\":199,\"position\":6,\"title\":\"Why you no stay done?\",\"updated_at\":\"2011-08-03T23:22:41Z\"},{\"completed\":false,\"id\":200,\"position\":7,\"title\":\"Wow\",\"updated_at\":\"2011-08-04T00:02:07Z\"},{\"completed\":false,\"id\":201,\"position\":8,\"title\":\"Hello World\",\"updated_at\":\"2011-08-04T00:02:11Z\"},{\"completed\":false,\"id\":202,\"position\":9,\"title\":\"GOLDEN GATE BRIDGE CATALYST,\",\"updated_at\":\"2011-08-04T00:44:19Z\"}]

我无法遍历对象。我能做到:

JSON.parse(list_items_open).each do |item|
  Rails.logger.info item.inspect
end

输出:

{"completed"=>false, "id"=>193, "position"=>0, "title"=>"Item X", "updated_at"=>"2011-08-03T21:16:19Z"}
{"completed"=>false, "id"=>197, "position"=>1, "title"=>"Item 2", "updated_at"=>"2011-08-03T21:17:11Z"}
{"completed"=>false, "id"=>192, "position"=>2, "title"=>"Item Z", "updated_at"=>"2011-08-03T21:16:17Z"}
{"completed"=>false, "id"=>196, "position"=>3, "title"=>"Item 1", "updated_at"=>"2011-08-03T21:17:09Z"}
{"completed"=>false, "id"=>194, "position"=>4, "title"=>"Item Y", "updated_at"=>"2011-08-03T21:16:21Z"}
{"completed"=>false, "id"=>195, "position"=>5, "title"=>"Item P", "updated_at"=>"2011-08-03T21:16:25Z"}
{"completed"=>false, "id"=>199, "position"=>6, "title"=>"Why you no stay done?", "updated_at"=>"2011-08-03T23:22:41Z"}
{"completed"=>false, "id"=>200, "position"=>7, "title"=>"Wow", "updated_at"=>"2011-08-04T00:02:07Z"}
{"completed"=>false, "id"=>201, "position"=>8, "title"=>"Hello World", "updated_at"=>"2011-08-04T00:02:11Z"}
{"completed"=>false, "id"=>202, "position"=>9, "title"=>"GOLDEN GATE BRIDGE CATALYST,", "updated_at"=>"2011-08-04T00:44:19Z"}

但我无法得到实际的身份证明:

JSON.parse(list_items_open).each do |item|
  Rails.logger.info item[:id]
end

什么都不返回。关于如何获取物品ID的建议?

由于

1 个答案:

答案 0 :(得分:15)

符号和字符串是不同的东西(除非你使用HashWithIndifferentAccess时),你应该使用字符串作为键:

JSON.parse(list_items_open).each do |item|
  Rails.logger.info item['id']
end

这是一个带有'id'密钥的哈希:

{ "id" => 193 }

这是一个带有:id密钥的哈希:

{ :id => 193 }