6

I have a javascript function I am using to convert some JSON data to an excel export. For the most part, everything is working just fine.

I noticed however that one of my column names now has a comma in it (intentional) LastName, FirstName.

With my existing code, its causing the header column to be separated and moved over into its own column when I expect it to be a single column header.

/**
 * Convert the JSON to a CSV File
 * @param {*} JSONData 
 * @param {*} ReportTitle 
 * @param {*} ShowLabel 
 */
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 = '';
    //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 in arrData[0]) {
            //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; i++) {
        var row = "";
        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }
        row.slice(0, row.length - 1);
        //add a line break after each row
        CSV += row + '\r\n';
    }

    if (CSV == '') {
        alert("Invalid data");
        return;
    }

    var csv = CSV;
    blob = new Blob([csv], {
        type: 'text/csv'
    });


    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, ReportTitle);
    } else {
        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    }


}

I believe my error is in the if (ShowLabel) { statement.

Is there a way I can ignore the commas in the header row so that my columns will remain aligned?

Error:

enter image description here

Desired:

enter image description here

Any thoughts on how to ignore the commas in the header row?

1
  • I mean, not splitting on a delimiter in CSV format is a bit odd. You could set it up to split the string on every other comma if the column is "Last Name, First Name", but you would have to be sure that each cell had the exact same format. A.e. no missing names. And of course, this would be very specific so changing the column name at any time would require a change in code. Commented Dec 3, 2018 at 15:24

1 Answer 1

16

I believe you should add quotes around your labels so the comma inside (the quotes) is not treated as a separator

for (var index in arrData[0]) {
    //Now convert each value to string and comma-seprated
    row += '\"' + index + '\",';
}

In your screenshot, Bob, Jones is correctly assigned to one cell although there's a comma. If you open the CSV file in Notepad for instance you should see Bob, Jones has quotes.

Sign up to request clarification or add additional context in comments.

3 Comments

That looks like it worked - I should have noticed that from the code lower down that had the same thing :/
How to do this for its below data not the header.
Thanks a lot! I have commas in my fields and those were dividing the single field into multiple columns. I have been looking at how to change the comma delimiter but not getting any solution. Whereas this worked perfectly. small thing eat my lots of time. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.