I am trying to extract some data that is being returned in a nested hash from Mailchimp. Here is a trimmed down version of the results I am getting. For each email there are multiple GROUPINGS and for each GROUPING there are multiple GROUPS.
My objective is to get this into a mysql table with a layout like: email_addr, list, grouping1_id, grouping1_name, group1_name, group1_interest, group2_name, group2_interest, grouping2_id, grouping2_name, etc. So there is one row per subscriber with all the grouping and group information.
{"email"=>"dummy@gmail.com", "merges"=>{"EMAIL"=>"dummy@gmail.com",
"GROUPINGS"=>[{"id"=>1, "name"=>"Grouping One", "groups"=>[{"name"=>"Group One",
"interested"=>false}, {"name"=>"Group", "interested"=>true},
{"name"=>"Group Three", "interested"=>true}]}, {"id"=>2, "name"=>"Grouping Two",
"groups"=>[{"name"=>"Group Four", "interested"=>false},
{"name"=>"Group Five", "interested"=>false}]}]}}
Right now, the code I have below runs and inserts the results of the nested blocks into the table but there is one row for each pass through the groups.each_with_index statement. My approach so far seems overly complicated but I am not sure of how to approach this to process the data correctly.
Any help is appreciated.
UPDATED: I cleaned up the logic a bit and separated the database writes into each level of the hash processing. Now the data is inserted and updated in the database correctly. Although this still feels very inelegant.
def organize_members_subs
@members_data = @members_subs["data"]
@members_data.each do |member|
@email_addr = member["email"]
@db.query("INSERT INTO db.details
(email_addr, list)
VALUES ('#{@email_addr}', '#{@list}' ) ")
groupings = member["merges"]["GROUPINGS"]
groupings.each_with_index do |grouping, index|
@groupings_name = grouping["name"]
@groupings_id = grouping["id"]
@groupings_label = "grp#{index}_"
@db.query("UPDATE db.details
SET grouping#{index}_id = '#{@groupings_id}'
, grouping#{index}_name = '#{@groupings_name}'
WHERE email_addr = '#{@email_addr}' ")
groups = member["merges"]["GROUPINGS"][index]["groups"]
groups.each_with_index do |group, index|
@group_name = group["name"]
@group_interested = group["interested"]
@db.query("UPDATE db.details
SET #{@groupings_label}group#{index}_name = '#{@group_name}'
, #{@groupings_label}group#{index}_int = '#{@group_interested}'
WHERE email_addr = '#{@email_addr}' ")
break if index == groups.length
end
break if index == groupings.length
end
end
end