Skip to content

Instantly share code, notes, and snippets.

@lrhazi
Last active August 14, 2022 12:36
Show Gist options
  • Save lrhazi/15570cb4ceddaa8b3587b51248b3853b to your computer and use it in GitHub Desktop.
Save lrhazi/15570cb4ceddaa8b3587b51248b3853b to your computer and use it in GitHub Desktop.
Fix Contact Groups IDs
import csv,sys
# contact groups export from source account (CSV)
fn1=sys.argv[1]
# contact groups export from target account (CSV)
fn2=sys.argv[2]
# Exported contacts from source account
contacts_csv_fn=sys.argv[3]
# Exported contacts from source account (Corrected)
contacts_csv_fn2=sys.argv[4]
labels1 = {}
labels2 = {}
for i,x in enumerate(csv.DictReader(open(fn1), quotechar="'"),1):
if x['groupType'] == 'USER_CONTACT_GROUP':
# print(f"1/{i}: {x['resourceName']} : {x['name']}")
labels1[x['name']] = x['resourceName']
for i,x in enumerate(csv.DictReader(open(fn2), quotechar="'"),1):
if x['groupType'] == 'USER_CONTACT_GROUP':
# print(f"2/{i}: {x['resourceName']} : {x['name']}")
labels2[x['name']] = x['resourceName']
labels = {}
for i,(name,resourceName) in enumerate(labels1.items(),1):
new_resourceName = labels2.get(name)
labels[name] = (resourceName,new_resourceName)
# print(f"{i}: {resourceName} --> {new_resourceName} : {name}")
contacts_new = []
for i,x in enumerate(csv.DictReader(open(contacts_csv_fn), quotechar="'"),1):
# User,resourceName,JSON
contact_json = x['JSON']
for (resourceName,new_resourceName) in labels.values():
resourceId = resourceName.split('/')[1]
new_resourceId = new_resourceName.split('/')[1]
contact_json = contact_json.replace(resourceId,new_resourceId)
contacts_new.append({'User': x['User'],'resourceName': x['resourceName'],'JSON': contact_json})
with open(contacts_csv_fn2, 'w', newline='') as csvfile:
fieldnames = ['User','resourceName','JSON']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames, quotechar="'")
writer.writeheader()
writer.writerows(contacts_new)
print(f"Done. Results in: {contacts_csv_fn2}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment