Create structured JSON object from CSV file in JavaScript?

前端 未结 3 919
鱼传尺愫
鱼传尺愫 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: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.

提交回复
热议问题