将活动记录结果转换为Json对象

时间:2013-07-02 09:13:06

标签: ruby-on-rails json

我有来自活动记录查询的输出

[{"image_id"=>1, "image_name"=> "image1", action_type"=>"Call", "count"=>2}, 
`{"image_id"=>1, "image_name"=> "image1","action_type"=>"sms", "count"=>1},  
 {"image_id"=>2, "image_name"=> "image2","action_type"=>"sms", "count"=>1} ]`

现在我希望将其转换为Json对象,如下所示

{ "1": {  "counts": { "call": 2,  "sms": 1 } , "title":'image1' },  
  "2": { "counts":  {"sms": 1} , 'title':'image2'}}

2 个答案:

答案 0 :(得分:1)

有两个受欢迎的图书馆都非常有用:

我个人更喜欢active_model_serializers。许多人不同意。

答案 1 :(得分:1)

请检查此代码。

@xx = [{"image_id"=>1, "image_name"=>"image1", "action_type"=>"Call", "count"=>2}, {"image_id"=>1, "image_name"=>"image1", "action_type"=>"sms", "count"=>1}, {"image_id"=>1, "image_name"=>"image1", "action_type"=>"sms", "count"=>1}]
@arr = []

@xx.each_with_index do |x, i|
    @arr << {(i+1).to_s.to_sym => {"counts" => {x["action_type"].to_sym => x["count"]}}}
end

respond_to do |f|
    f.json {render :json => @arr}
end