将密钥为对象的哈希传递给JSON?

时间:2012-11-26 04:35:15

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

我试图通过JSON将哈希传递给Javascript,其中键是ruby对象,值是对象数组。对象数组传输得很好,但是键被转换为类的字符串。

以下是一个例子:

[4] pry(#<User>)> x = find_all_sections.collect { |s| { s => s.find_all_events_id_and_title } }
=> [{#<Section id: 58, course_id: 12, section_number: 3, semester_id: 1>} =>
   [{:id=>37, :title=>"Event 37"},
    {:id=>40, :title=>"Event 40"},
    {:id=>9, :title=>"Event 9"},
    {:id=>10, :title=>"Event 10"},
    {:id=>16, :title=>"Event 16"},
    {:id=>38, :title=>"Event 38"}, etc...

将此转换为json的结果是(您只需要查看字符串的前几个字符,看它不是对象,而是对象的to_s:

[11] pry(#<User>)> x.to_json
=> "[{\"#<Section:0x007fa475b52f68>\":[{\"id\":37,\"title\":\"Event 37\"},{\"id\":40,\"title\":\"Event 40\"},{\"id\":9,\"title\":\"Event 9\"},{\"id\":10,\"title\":\"Event 10\"},{\"id\":16,\"title\":\"Event 16\"},{\"id\":38,\"title\":\"Event 38\"},{\"id\":49,\"title\":\"Event 49\"},{\"id\":39,\"title\":\"Event 39\"},{\"id\":15,\"title\":\"Event 15\"},{\"id\":25,\"title\":\"Event 25\"},{\"id\":11,\"title\":\"Event 11\"},{\"id\":4,\"title\":\"Event 4\"},{\"id\":22,\"title\":\"Event 22\"},{\"id\":1,\"title\":\"Event 1\"},{\"id\":23,\"title\":\"Event 23\"},{\"id\":8,\"title\":\"Event 8\"},{\"id\":13,\"title\":\"Event 13\"},{\"id\":26,\"title\":\"Event 26\"},{\"id\":46,\"title\":\"Event 46\"},{\"id\":20,\"title\":\"Event 20\"},{\"id\":31,\"title\":\"Event 31\"},{\"id\":6,\"title\":\"Event 6\"},{\"id\":18,\"title\":\"Event 18\"},{\"id\":41,\"title\":\"Event 41\"},{\"id\":7,\"title\":\"Event 7\"},{\"id\":43,\"title\":\"Event 43\"},{\"id\":45,\"title\":\"Event 45\"},{\"id\":24,\"title\":\"Event 24\"},{\"id\":2,\"title\":\"Event 2\"},{\"id\":44,\"title\":\"Event 44\"},{\"id\":29,\"title\":\"Event 29\"},{\"id\":28,\"title\":\"Event 28\"},{\"id\":5,\"title\":\"Event 5\"},{\"id\":3,\"title\":\"Event 3\"},{\"id\":27,\"title\":\"Event 27\"}]},

如何实现JSON数据以保持密钥对象的完整性?

1 个答案:

答案 0 :(得分:0)

你做不到。键始终是JavaScript中的字符串。此外,JSON spec表示键必须始终具有单个双引号字符串文字的形式。