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

有两个非常有用的流行库:

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

于 2013-07-02T09:26:00.897 回答
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 回答