Search code examples
javascriptjsoncsvobjectpapaparse

Add header to object or csv string


I'm using Papaparse with my csv (no header) string to give me an array of objects. I can parse the string without a header then change the keys or I can add a header string to my csv string and then parse that. I haven't had luck with either approach

var csvString = txtArea.value.trim();
var header = 'Header1,Header2,Header3,Header4';
csvString = header+csvString;
var objects = Papa.parse(csvString,{header:true});

Solution

  • You must insert a linebreak \n between header and the CSV :

    csvString = header+'\n'+csvString;
    

    Then your code works and produces objects on the form

    { 
       "Header1" : "a",
       "Header2" : "b",
       ..
    }
    

    demo -> http://jsfiddle.net/rf1h0h10/