Create structured JSON object from CSV file in JavaScript?

前端 未结 3 918
鱼传尺愫
鱼传尺愫 2021-01-15 12:45

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 havin

相关标签:
3条回答
  • 2021-01-15 12:56

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

    0 讨论(0)
  • 2021-01-15 12:59

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

    This is assuming the structure of the CSV is always the same.

    0 讨论(0)
  • 2021-01-15 13:16

    If you are struggling to parse data, you can also use PapaParse, it has a lot of configurations and it's pretty easy to use:

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

    See more information at https://www.papaparse.com/demo

    0 讨论(0)
提交回复
热议问题