Skip to content

Instantly share code, notes, and snippets.

@johndavidsimmons
Created October 1, 2019 17:09
Show Gist options
  • Select an option

  • Save johndavidsimmons/f2f7e39991a0ddb455d1ab3cc31136a9 to your computer and use it in GitHub Desktop.

Select an option

Save johndavidsimmons/f2f7e39991a0ddb455d1ab3cc31136a9 to your computer and use it in GitHub Desktop.
The function for converting csv 2 json
const button = document.querySelector("#convert");
const outputTextarea = document.querySelector("#outputdata");
button.addEventListener("click", function() {
let inputData = document.querySelector("#inputdata").value;
// remove newlines
let cleanedData = inputData.replace(/\n/g, ",");
// make it an array
let stringArray = cleanedData.split(",")
// start json string
let outputString = '{'
for (let index = 0; index < stringArray.length; index+=2) {
const element = stringArray[index];
const next = stringArray[index+1]
outputString += `"${element}" : "${next}",`
}
// remove trailing comma and end json string
let jsonString = outputString.slice(0,-1)+ "}";
// put output string into output text area
document.querySelector("#outputdata").value = jsonString;
});
// copy output to clipboard on click
outputTextarea.addEventListener("click", function() {
if (outputTextarea.value) {
let copytext = outputTextarea;
copytext.select();
document.execCommand("copy");
document.getElementById("copyalert").style.display = "";
// send click event
gtag('event', "click", {
'event_category': "convert_data",
});
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment