从JavaScript中的CSV文件创建结构化JSON对象? [英] Create structured JSON object from CSV file in JavaScript?

查看:85
本文介绍了从JavaScript中的CSV文件创建结构化JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a JSON object from the contents of a CSV file. The CSV file is loaded locally via the FileReader API and that seems to work, however I am having trouble structuring the JSON in the desired way.

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

My code for loading the CSV file looks like this:

<!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数据结构化为所需的格式,我尝试了以下操作,但是对我来说不起作用:

The code above allows me to load the contents of the CSV file and display them on the current page. To structure the CSV data into the desired format above I tried the following, however it didn't work to me:

<!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对象?任何建议将不胜感激

How can I acquire my expected JSON object(s)? Any suggestions would be appreciated

推荐答案

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

One approach to this would be to iterate through your input CSV data on increments of "6" (where 6 represents the number of different bits of data for each student) to capture all student data per CSV row, and then populate an array of structured JSON objects in the desired format like so:

/* 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);

这篇关于从JavaScript中的CSV文件创建结构化JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆