目前我正在创建一个JSON对象,如下所示:
@comments = Array.new
comments.collect do |comment|
@comments << {
:id => comment.id,
:content => html_format(comment.content),
:created_at => comment.created_at
}
end
@comments.to_json
这会返回这样的内容:
[{"created_at":"2011-03-02T09:17:27-08:00","content":"<p>Random.......</p>","id":734}, {"created_at":"2011-03-02T09:17:27-08:00","content":"<p>asdasd.......</p>","id":714}, {"created_at":"2011-03-01T09:17:27-08:00","content":"<p>Random.......</p>","id":134}, {"created_at":"2011-03-01T02:17:27-08:00","content":"<p>dasdasdasdasd.......</p>","id":3124}]
这里的问题是我需要包含一些非数组的其他项目。我想要的是JSON对象看起来像这样:
[comments: {"created_at":"2011-03-02T09:17:27-08:00","content":"<p>Random.......</p>","id":734}, {"created_at":"2011-03-02T09:17:27-08:00","content":"<p>asdasd.......</p>","id":714}, {"created_at":"2011-03-01T09:17:27-08:00","content":"<p>Random.......</p>","id":134}, {"created_at":"2011-03-01T02:17:27-08:00","content":"<p>dasdasdasdasd.......</p>","id":3124}, last_load: "123123123123", last_view: "zxczcxzxczxc"]
关于如何获取上述内容并将其展开以传递除注释数组以外的其他项目的任何想法?
谢谢!
答案 0 :(得分:5)
将列表添加到哈希中,然后在哈希上调用to_json
。
> a = [1,2,3]
=> [1, 2, 3]
> h = {:comments => a, :foo => "bar"}
=> {:foo=>"bar", :comments=>[1, 2, 3]}
> h.to_json
=> "{\"foo\":\"bar\",\"comments\":[1,2,3]}"