从JavaScript中的CSV文件创建结构化JSON对象?

时间:2019-02-25 18:50:25

标签: javascript html json filereader

我想从CSV文件的内容创建JSON对象。 CSV文件是通过FileReader API在本地加载的,这似乎可以正常工作,但是我无法以所需的方式构造JSON。

我用于加载CSV文件的代码如下:

<!DOCTYPE html>
<html>
    <body>
        <p>Select local CSV File:</p>
        <input id="csv" type="file">
        <output id="out"> input file content</output>
        <script>
            var fileInput = document.getElementById("csv"),
            readFile = function () {
                var reader = new FileReader();
                reader.onload = function () {

                    // Display CSV file contents
                    document.getElementById('out').innerHTML = reader.result;
                };

                reader.readAsBinaryString(fileInput.files[0]);
            };
            fileInput.addEventListener('change', readFile);
        </script>
    </body>>
</html>

上面的代码使我可以加载CSV文件的内容并将其显示在当前页面上。要将CSV数据结构化为所需的格式,我尝试了以下操作,但对我而言无效:

<!DOCTYPE html>
<html>
    <body>
        <script>
            var fileReader = new FileReader();
            function getFile(inputFile) {
            let file = inputFile.files[0];
            fileReader.readAsText(file);
            }
            function csvJSON(csv){
            var lines=csv.split("\n");
            var result = [];
            var headers=lines[0].split(",");
            for(var i=1;i<lines.length;i++){
                var obj = {};
                var currentline=lines[i].split(",");
                for(var j=0;j<headers.length;j++){
                    obj[headers[j]] = currentline[j];
                }
                result.push(obj);
            }
            return JSON.stringify(result); //JSON
            }
            function readFile(evt) {
            let parsed = csvJSON(evt.target.result);
            return parsed;
            }
        </script>
    </body>
</html>

如何获取所需的JSON对象?任何建议将不胜感激

3 个答案:

答案 0 :(得分:1)

var csv = '"Timestamp","Enter First Name:","Enter Middle Initial","Enter Last Name:","Enter UIN:","Are you attending the event?"\n"2019/02/22 12:41:56 PM CST","Jonathan","Samson","Rowe","123456789","No"\n"2019/02/22 12:44:56 PM CST","phil","Aspilla","beltran","123456788","Yes"';

var csvJSON = function(csv) {
  let vals = csv.split('\n'), ret = [];
  for( let i = 1, len = vals.length; i < len; i++ ){
    let person = vals[i].split(',');
    ret.push({
      uin : person[4],
      studentInfo : {
        firstName : person[1],
        middleName : person[2],
        lastName : person[3],
        rsvpStatus : person[5]
      }
    });
  }
  return JSON.stringify(ret);
}

console.log(csvJSON(csv));

这是假设CSV的结构始终相同。

答案 1 :(得分:1)

如果您正在努力解析数据,则也可以使用PapaParse,它具有很多配置,并且非常易于使用:

// Parse CSV string
var data = Papa.parse(csv);

https://www.papaparse.com/demo上查看更多信息

答案 2 :(得分:1)

一种解决方法是迭代输入的CSV数据以“ 6”为增量(其中6表示每个学生的不同数据位数)以捕获每个CSV行的所有学生数据,然后填充一个所需格式的结构化JSON对象数组,如下所示:

/* Helper function to perform the CSV to JSON transform */
function convertToJson(inputCsv) {

  /* Split input string by `,` and clean up each item */
  const arrayCsv = inputCsv.split(',').map(s => s.replace(/"/gi, '').trim())

  const outputJson = [];

  /* Iterate through input csv at increments of 6, to capture entire CSV row 
     per iteration */
  for (let i = 6; i < arrayCsv.length; i += 6) {

    /* Extract CSV data for current row, and assign to named variables */
    const [date, firstName, middleName, lastName, uin, rsvpStatus] = 
    arrayCsv.slice(i, i + 6)
    
    /* Populate structured JSON entry for this CSV row */
    outputJson.push({
      uin,
      studentInfo: {
        firstName,
        middleName,
        lastName,
        rsvpStatus
      }
    });
  }

  return outputJson;
}

/* Input CSV data from your exsiting code */
const csv = `"Timestamp", "Enter First Name:", "Enter Middle Initial", 
"Enter Last Name:", "Enter UIN:", "Are you attending the event?",
  "2019/02/22 12:41:56 PM CST", "Jonathan", "Samson", "Rowe", "123456789", 
"No", "2019/02/22 12:44:56 PM CST", "phil", "Aspilla", "beltran", "123456788", 
"Yes"`

const json = convertToJson(csv);

console.log(json);