pramodtech
pramodtech

Reputation: 6270

Convert active record result into Json object

I have below output from active record query

[{"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} ]`

Now I want this to be converted into Json object like below

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

Upvotes: 2

Views: 1369

Answers (2)

Bachan Smruty
Bachan Smruty

Reputation: 5734

Please check this code.

@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

Upvotes: 1

ezkl
ezkl

Reputation: 3851

There are two popular libraries that are both very helpful:

I prefer active_model_serializers, personally. Many disagree.

Upvotes: 1

Related Questions