Created
October 28, 2021 17:08
-
-
Save ak--47/82cd524418de038de1022d2de2db798e to your computer and use it in GitHub Desktop.
Google Sheets to Mixpanel (lookup table)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// written for google's app script inside google sheets | |
// https://developers.google.com/apps-script/guides/sheets | |
function syncLookupTable() { | |
console.log('syncing lookup table!') | |
//credentials | |
const credentials = { | |
groupKey : `{{ your group key for existing lookup table }}`, | |
serviceAcct: `{{ service acct username }}`, | |
pass : `{{ service acct pass }}`, | |
project_id : `{{ mixpanel project id }}` | |
} | |
//docs: https://developer.mixpanel.com/reference/lookup-tables | |
const endpoint = `https://api.mixpanel.com/lookup-tables/${credentials.groupKey}?project_id=${credentials.project_id}` | |
const auth = `${credentials.serviceAcct}:${credentials.pass}` | |
//get sheet data | |
const sheet = SpreadsheetApp.getActiveSheet(); | |
const data = sheet.getDataRange().getValues(); | |
//console.log(data) | |
//build lookup table | |
const headers = data.shift(); | |
const fullLookupTableData = buildLookupTable(headers, data); | |
//send to mixpanel | |
const options = { | |
'method' : 'put', | |
'contentType': 'text/csv', | |
'payload' : fullLookupTableData, | |
'headers' : { | |
Authorization : `Basic ${Utilities.base64Encode(auth)}`, | |
Accept: 'application/json' | |
} | |
}; | |
const response = UrlFetchApp.fetch(endpoint, options); | |
console.log(`mixpanel response:`) | |
console.log(JSON.stringify(JSON.parse(response.getContentText()), null, 2)); | |
} | |
/* | |
lookup tables expects data to look like this: | |
id,artist,genre,is_platinum,name,num_listens,release_date,is_top_40 | |
c994bb,Drake,Pop,True,Hotline Bling,1700000000,2015-10-18T22:00:00,true | |
d8d949,Gipsy Kings,Flamenco,False,Bamboleo,1170000,1987-07-12T05:00:00,false | |
a43fb8,Daft Punk,House,False,Aerodynamic,41000000,2001-03-12T07:30:00,false | |
*/ | |
function buildLookupTable(headers, data) { | |
let finalCSV = ``; | |
finalCSV += `${headers}\n` | |
for (const row of data) { | |
finalCSV += `${row.join(',')}\n` | |
} | |
finalCSV.trim() | |
return finalCSV | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment