parse json to .csv in js - javascript

I found this script (works well) except that I want to skip few columns (i just want to extract column 1,2,3,9) so I have this :
$(document).ready(function(){
$('button').click(function(){
var data = $('#txt').val();
if(data == '') return;
JSONToCSVConvertor(data, "Agenda", true);
});
});
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object'
? JSON.parse(JSONData)
: JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index = 0; i<arrData.length-1; index++) {
if (index == 4 || index == 5 || index == 6 || index == 7 || index == 8) {
continue;
}
else{
//Now convert each value to string and comma-seprated
row += index + ';';
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length-1; i++) {
if (i == 4 || i == 5 || i == 6 || i == 7 || i == 8) {
continue;
}
else{
var row = "";
}
//2nd loop will extract each column and convert it in string comma-seprated
for (var j = 0; i<arrData.length-1; j++) {
if (j == 4 || j == 5 || j == 6 || j == 7 || j == 8) {
continue;
}
else{
row += '"' + arrData[i][j] + '";';
}
}
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "Formapelec_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
It's supposed to generate a .csv with just column 1,2,3 & 9 but there's nothing in return. I tried different things with if() {continue} but I either have a return with all the columns or no return at all.

for (var i = 0; i < arrData.length-1; i++) {
//2nd loop will extract each column and convert it in string comma-seprated
for (var j = 0; j<arrData[i].length; j++) {
if (j == 4 || j == 5 || j == 6 || j == 7 || j == 8) {
continue;
}
else{
row += '"' + arrData[i][j] + '";';
}
}
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
you skipped rows, your second for was also wrong(incrementing j, but checking i, this would either run for ever or never run

//1st loop is to extract each row
for (var i = 0; i < arrData.length-1; i++) {
if (i == 4 || i == 5 || i == 6 || i == 7 || i == 8) {
continue;
}
You are skipping rows too, that if shouln't be there

Related

Get array values from column

If my function gets the values of one column, say column I, how can I tell it to instead get the values of the column to the right (J) instead of I:K?
function headerSearch(e, activeCell, activeRow, activeCol, data, mode, secMode, terMode) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var foundValues = [];
var forConR = data.length;
var forConC = data[0].length;
Logger.log("data[0] = " + data[0]);
for (var i = 1; i < forConR; i++) {
for (var j = 0; j < forConC; j++) {
if (activeCell != "" && activeCol == 2 && data[0][j].indexOf(mode) > -1) {
if (activeCell.getValue() == data[0][j]) {
foundValues.push(data[i][j]);
}
} else if (activeCell != "" && activeCol == 3 && data[0][j].indexOf(mode) > -1 && data[i][j] != "") {
foundValues.push(data[i][j]);
Logger.log("foundValues = " + foundValues);
}
}
}
if (foundValues != "") {
var validationRule = SpreadsheetApp.newDataValidation().requireValueInList(foundValues).build();
activeCell.offset(0, 1).setDataValidation(validationRule);
}
}
EDIT:
I tried adding foundValues.push(data[i][j+1]); which gets me out of the first column (I), but then of course adds the NEXT column (L) that I don't want either. I'm just not sure how to isolate the column index. Once I figure that out, I'm sure it's just a matter of adding +1 or something to OFFSET to the column to the right.
You have two for loops - one of them iterating through all rows, the second through all columns of data
What you want instead is to retrieve only ONE column of data rather than iterating through ALL of them
You can do it by simply dropping the second for loop and instead hardcoding the value for j
If you are itnerested in the second column of your range - the column index should be 1 (since array indices start with 0)
Without having a deeper knowledge of the purpose of your if conditions and assuming that you use them only to assess the value in column J, you can modify your code as following:
...
for (var i = 1; i < forConR; i++) {
var j = 1;
if (activeCell != "" && activeCol == 2 && data[0][j].indexOf(mode) > -1) {
if (activeCell.getValue() == data[0][j]) {
foundValues.push(data[i][j]);
}
} else if (activeCell != "" && activeCol == 3 && data[0][j].indexOf(mode) > -1 && data[i][j] != "") {
foundValues.push(data[i][j]);
Logger.log("foundValues = " + foundValues);
}
}
...
I rearranged my if statements and added one to isolate the "mode" column (B) selected. At that point, I could add j + 1 to get the following column values for the next data validation selection.
function headerSearch(e, activeCell, activeRow, activeCol, data, mode, secMode, terMode) {
var foundValues = [];
var forConR = data.length;
var forConC = data[0].length;
if (activeCell != "") {
for (var i = 1; i < forConR; i++) {
for (var j = 0; j < forConC; j++) {
if (data[0][j] == mode && data[i][j] != "") {
var modeCol = j;
}
if (activeCol == 2 && data[i][j] != "") {
if (activeCell.getValue() == data[0][j]) {
foundValues.push(data[i][j]);
}
} else if (activeCol == 3 && data[0][j].indexOf(mode) > -1 && data[i][j] != "" && data[0][modeCol + 1].indexOf(mode) > -1) {
foundValues.push(data[i][modeCol + 1]);
} else if (activeCol == 4 && data[0][j].indexOf(mode) > -1 && data[i][j] != "" && data[0][modeCol + 2].indexOf(mode) > -1) {
foundValues.push(data[i][modeCol + 2]);
}
}
}
}
if (foundValues != "") {
var validationRule = SpreadsheetApp.newDataValidation().requireValueInList(foundValues).build();
activeCell.offset(0, 1).setDataValidation(validationRule);
}
}

How to validate an uploaded CSV file if rows are present or not in javascript

I have a CSV file which should be validated on uploading in the form. 'Error' should pop up if any rows are missing in the column else it should show 'validated'. I am new to java script and have tried below code but even though rows are not empty the code is showing 'error'. can somebody help me out in identifying where i am going wrong?
The CSV file is as follows:
serial.no. name
1 abc
2 def
if any row is missing it should show 'error' else 'validated'
This is my javascript code:
<script>
function checkfilesize()
{
if (document.getElementById("myFile").files[0].size > 100000) // about 8 kb here,20971522 mb for bytes.
{
alert("File size must under 10kb!");
document.getElementById("myFile").value="";
return;
}
}
function newDoc()
{
var flag = 0;
var fileUpload = document.getElementById("myFile");
var reader = new FileReader();
reader.onload = function (e)
{
var rows = e.target.result.split("\n");
for (var i = 1; i < rows.length; i++)
{
var cells = rows[i].split(",");
for (var j = 0; j <cells.length; j++)
{
if(cells[j]=="")
{
window.alert("ERROR");
flag=1;
break;
}
}
if(flag==1)
break;
}
if (flag)
window.alert("ERROR");
else
window.alert("VALIDATED");
}
reader.readAsText(fileUpload.files[0]);
}
</script>
I tried reproduce your code, it worked well if your csv file correct format.
With error case, you need add check for return character cells[j] == "\r" in case empty line in csv file.
If dont check cells[j] == "\r" your code still show VALID while having empty line in csv file.
if (cells[j] == "" || cells[j] == "\r") {
window.alert("ERROR");
flag = 1;
break;
}
Ensure that your csv file content correct as
serial.no.,name
1,abc
2,def
This content is incorrect (have comma after second item)
serial.no.,name
1,abc,
2,def
function checkfilesize() {
if (document.getElementById("myFile").files[0].size > 100000) // about 8 kb here,20971522 mb for bytes.
{
alert("File size must under 10kb!");
document.getElementById("myFile").value = "";
return;
}
}
function newDoc() {
var flag = 0;
var fileUpload = document.getElementById("myFile");
var reader = new FileReader();
reader.onload = function (e) {
var rows = e.target.result.split("\n");
for (var i = 1; i < rows.length; i++) {
var cells = rows[i].split(",");
if(cells.length < 2){
flag = 1;
break;
}
for (var j = 0; j < cells.length; j++) {
if (cells[j] == "" || cells[j] == "\r") {
window.alert("ERROR");
flag = 1;
break;
}
}
if (flag == 1)
break;
}
if (flag)
window.alert("ERROR");
else
window.alert("VALIDATED");
}
reader.readAsText(fileUpload.files[0]);
}
<input type="file" id="myFile" />
<button onclick="checkfilesize();">Check Size</button>
<button onclick="newDoc();">Check Format</button>

Check and alert for the null value

I need to check for the null values and alert them if there are any before getting saved. I have used this code but I am not able to alert the null values instead it is getting saved . .
function fn_publish() {
var SessionNames = getParameterByName('SessionName');
var MenuType = getParameterByName('MenuType');
var Date = getParameterByName('ForDate');
var publish = "Y";
Dates = Date.split("-");
Date = Dates[1] + "/" + Dates[2] + "/" + Dates[0];
var rows = [];
cols = document.getElementById('product_table').rows[1].cells.length - 1;
table = document.getElementById('product_table');
for (var i = 1; i <= cols; i++) {
for (var j = 0, row; row = table.rows[j]; j++) {
if (j == 0) {
cust = row.cells[i].innerText;
alert(cust);
} else if (j == 1) {
catlg = row.cells[i].innerText;
alert(catlg);
} else {
if (typeof (row.cells[i]) != "undefined") {
if (row.cells[i].innerText != "") {
//alert(SessionNames+"::"+MenuType+"::"+Date+"::"+catlg+"::"+row.cells[0].innerText+"::"+row.cells[i].innerText+"::"+cust+"::"+publish);
fn_insert(SessionNames, MenuType, Date, catlg, row.cells[0].innerText, row.cells[i].innerText, cust, publish);
} else {
jAlert("Please select a product", "ok");
return false;
}
}
}
}
}
jAlert("Menu Published", "ok");
}
if (row.cells[i].innerText != "") {
May be the cells are containing empty space in that. Better trim ad then compare.
if (row.cells[i].innerText.trim() !== "") {
Also instead of innerText use textContent which is common in most modern browsers.
if (row.cells[i].textContent.trim() !== "") {

Prevent duplicate row on jquery append

I have this js for appending fields, checking blank fields, and to prevent duplicate values at rows. But it only works for checking blank fields. Does this code have any mismatch at placement or something else? Thanks.
<script>
count4 = 1;
function appendCertification(){
var certification = $('#certification').val();
var skillSector = $('#skillSector').val();
var issueDate = $('#issueDate').val();
var expirDdate = $('#expiryDate').val();
if(cerfication == "" || skillSector == "" || issueDate == "" || expiryDate == "") {
alert("please fill minimum 1 row");
return false;
}
for (var i = 0, row; row = document.getElementById("#certificationTable").rows[i]; i++) {
var fields = new Array();
for (var j = 0, col; col = row.cells[j]; j++) {
fields[j] = col.innerHTML;
}
if(certification == fields[0] && skillSector == fields[1] && issuedate == fields[2] && expireddate == fields[3]) {
alert("Duplicate row");
return false;
}
}
var field = "<tr><td>"+certification+"</td><td>"+skillSector+"</td><td>"+issueDate+"</td><td>"+expiryDate+"</td><input type='hidden' name='certificationVal[]' value='"+certification+"'><input type='hidden' name='sectorSkillVal[]' value='"+sectorSkill+"'><input type='hidden' name='issueDateVal[]' value='"+issueDate+"'><input type='hidden' name='expiryDateVal[]' value='"+expiryDate+"'></tr>";
$("#certificationTable tbody").append(field);
count++;
};
function clearform(){
$("#certificationTable tbody").html("");
};
</script>
not considering the mistyping of the variable names, document.getElementById use the id of the element without the #
so the error is in this row
for (var i = 0, row; row = document.getElementById("#certificationTable").rows[i]; i++) {
it should be
for (var i = 0, row; row = document.getElementById("certificationTable").rows[i]; i++) {

Javascript Function not working in firefox or safari

I am trying to display the sum of transaction at the bottom of the page.
function doTotal() {
var Stuff = document.getElementsByTagName("input");
var theTotal = new Number(0);
for (var i = 0; i < Stuff.length; i++) {
if (Stuff[i].getAttribute('type') == 'text') {
if ((Stuff[i].value != '') && (IsNumeric(Stuff[i].value) == true) && (Stuff[i].name.substr(0, 8) == 'txtValue')) {
theTotal = theTotal + parseFloat(Stuff[i].value);
}
}
}
document.getElementById("tdTotal").innerHTML = "R " + theTotal.toFixed(2);
frm.txtTotal.value = theTotal.toFixed(2);
//alert(theTotal);
}
EDIT:
Ofc Im stupid, it cant work since value from input is always string. So I change the condition. Now it should work:
function doTotal() {
var stuff = document.getElementsByTagName("input");
var theTotal = 0;
for (var i = 0; i < stuff.length; i++) {
if (stuff[i].getAttribute('type') == 'text') {
if ((stuff[i].value != '') && !isNaN(stuff[i].value) && (typeof stuff[i].name.substr(0, 8) === "string")) {
theTotal += parseFloat(stuff[i].value);
}
}
}
// document.getElementById("tdTotal").innerHTML = "R " + theTotal.toFixed(2);
// frm.txtTotal.value = theTotal.toFixed(2);
alert(theTotal);
}
Try it there: http://jsfiddle.net/windkiller/9dvRS/
EDIT2:
Debug it, so you can see what condition didnt pass wrong:
function doTotal() {
var stuff = document.getElementsByTagName("input");
var theTotal = 0;
var i = 0;
alert(stuff[i].getAttribute('type') == 'text');
alert(stuff[i].value != '');
alert(!isNaN(stuff[i].value));
alert(typeof stuff[i].name.substr(0, 8) === "string");
}

Categories

Resources