In JavaScript, how can I ignore blank lines when converting csv to json

时间:2016-06-18 20:22:52

标签: javascript json regex csv

I'm working on a project that requires me to convert csv to json. I found a fiddle here. The only problem is that if you add blank lines at the end and convert to json, it will return back the blank lines as objects.

e.g.,

"Id","UserName"
"1","Sam Smith"
"2","Fred Frankly"
"1","Zachary Zupers"



...

will return

[{"Id":"1","UserName":"Sam Smith"},
{"Id":"2","UserName":"Fred Frankly"},
{"Id":"1","UserName":"Zachary Zupers"},
{"Id":""},
{"Id":""}]

Other answers on stack overflow appear to be related to other programming languages and, though they appear to answer the asker's question, they solve the problem without explanation. Bonus warm fuzzies if you can explain how your answer works.

1 个答案:

答案 0 :(得分:4)

添加.trim()以删除strData

周围的空白区域

strData = strData.trim();

http://jsfiddle.net/AZFvQ/909/

// Source: http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.

function CSVToArray(strData, strDelimiter) {
    strData = strData.trim();
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ",");
    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp((
    // Delimiters.
    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
    // Quoted fields.
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
    // Standard fields.
    "([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");
    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];
    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;
    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec(strData)) {
        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[1];
        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push([]);
        }
        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[2]) {
            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[2].replace(
            new RegExp("\"\"", "g"), "\"");
        } else {
            // We found a non-quoted value.
            var strMatchedValue = arrMatches[3];
        }
        // Now that we have our value string, let's add
        // it to the data array.
        arrData[arrData.length - 1].push(strMatchedValue);
    }
    // Return the parsed data.
    return (arrData);
}

function CSV2JSON(csv) {
    var array = CSVToArray(csv);
    var objArray = [];
    for (var i = 1; i < array.length; i++) {
        objArray[i - 1] = {};
        for (var k = 0; k < array[0].length && k < array[i].length; k++) {
            var key = array[0][k];
            objArray[i - 1][key] = array[i][k]
        }
    }

    var json = JSON.stringify(objArray);
    var str = json.replace(/},/g, "},\r\n");

    return str;
}

$("#convert").click(function() {
    var csv = $("#csv").val();
    var json = CSV2JSON(csv);
    $("#json").val(json);
});

$("#download").click(function() {
    var csv = $("#csv").val();
    var json = CSV2JSON(csv);
    window.open("data:text/json;charset=utf-8," + escape(json))
});
#heading { font-size: x-large; font-weight: bold; }
.text { width: 99%; height: 200px; }
.small { font-size: small; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>CSV to JSON</title>
</head>
<body>
    <p id="heading">CSV to JSON Converter</p>
    <p class="small"><a href="http://jsfiddle.net/sturtevant/vUnF9/" target="_blank">JSON to CSV Converter</a>
    <hr />
    <p>Paste Your CSV Here:</p>
    <textarea id="csv" class="text">"Id","UserName"
"1","Sam Smith"
"2","Fred Frankly"
"1","Zachary Zupers"</textarea>
    <br />
    <button id="convert">Convert to JSON</button>
    &nbsp;&nbsp;
    <button id="download">Download JSON</button>
    <textarea id="json" class="text"></textarea>
    <p>Based on code posted <a href="http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm" target="_blank">here on Ben Nadel's blog</a></p>
</body>
</html>

新输出

[{"Id":"1","UserName":"Sam Smith"},
{"Id":"2","UserName":"Fred Frankly"},
{"Id":"1","UserName":"Zachary Zupers"}]
相关问题