2

アクティブレコードクエリからの出力は以下のとおりです

[{"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'}}
4

2 に答える 2

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
于 2013-07-02T09:34:16.397 に答える