使用“json”gem在Ruby中解析JSON时,某些值为nil(已设置)

时间:2011-12-13 15:46:08

标签: ruby-on-rails ruby json gem

当我在rails控制台中解析以下json时,contact_person_id为零,即使它是“c221c0f96670db455a174f1f30ffef1a”。我正在使用普通的“json”宝石。我试图使用其他一些库,例如“yajl_ruby”,但后来其他东西破了。有谁知道为什么会这样?

ActiveSupport::JSON.decode '{"_id":"a042b081278fc535f50fd3f4ea695848","_rev":"7-435d6ef891d2d354a7233674c483194b","created_at":"2011-12-12T18:39:19Z","updated_at":"2011-12-12T22:34:35Z","contact_person_id":"c221c0f96670db455a174f1f30ffef1a","first_person_in_authority_id":null,"second_person_in_authority_id":null,"name":"","street":"","postcode":"","city":"","ruby_class":"Community"}'

=> #<Community _id: "a042b081278fc535f50fd3f4ea695848", _rev: "7-435d6ef891d2d354a7233674c483194b", created_at: Mon, 12 Dec 2011 18:39:19 UTC +00:00, updated_at: Mon, 12 Dec 2011 22:34:35 UTC +00:00, contact_person_id: nil, first_person_in_authority_id: nil, second_person_in_authority_id: nil, name: "", street: "", postcode: "", city: "", regional_chirch: nil, deanery: nil, chirch_district: nil, state: nil, urban_district: nil, county: nil, administrative_district: nil> 

1 个答案:

答案 0 :(得分:1)

我无法通过以下版本确认此问题:

ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin10.0.0]
activesupport (3.1.3)

我使用了以下代码段:

irb(main):003:0> ActiveSupport::JSON.decode '{"_id":"a042b081278fc535f50fd3f4ea695848","_rev":"7-435d6ef891d2d354a7233674c483194b","created_at":"2011-12-12T18:39:19Z","updated_at":"2011-12-12T22:34:35Z","contact_person_id":"c221c0f96670db455a174f1f30ffef1a","first_person_in_authority_id":null,"second_person_in_authority_id":null,"name":"","street":"","postcode":"","city":"","ruby_class":"Community"}'
=> {"city"=>"", "name"=>"", "created_at"=>"2011-12-12T18:39:19Z", "postcode"=>"", "first_person_in_authority_id"=>nil, "_rev"=>"7-435d6ef891d2d354a7233674c483194b", "updated_at"=>"2011-12-12T22:34:35Z", "_id"=>"a042b081278fc535f50fd3f4ea695848", "street"=>"", "contact_person_id"=>"c221c0f96670db455a174f1f30ffef1a", "second_person_in_authority_id"=>nil, "ruby_class"=>"Community"}
irb(main):004:0> _['contact_person_id']
=> "c221c0f96670db455a174f1f30ffef1a"

我认为问题在于您的代码库,即Community模型。 要检查的事项:

  • 是否有一些after_initialization挂钩?
  • 是否有自定义contact_person_id= setter?
  • contact_person是否必须与ID c221c0f96670db455a174f1f30ffef1a相关联?

没有任何进一步的信息,我很抱歉我无法给你更好的答案。