Search code examples
javascriptjsonpapaparse

Papa Parse: Save JSON Output Locally


I have the following code:

Papa.parse("/drivencarstock.csv", {
  download: true,
  header: true,
    step: function(row) {
        console.log("Row:", row.data);
    },
    complete: function() {
        console.log("All done!");
    }
});

As you can see I am parsing the 'drivencarstock.csv' file and it outputs into my console perfectly however now I am just wondering how I can output this as a json file on my server?

I can't see how this might be done?

Thanks, Nick


Solution

  • The first step would be to actually collect the parsed data in a variable, such as an array. Then in the step you'd add the row.data to this array. Once complete you could POST the data using AJAX.

    For example:

    //  create the array to hold the data
    var myRows = [];
    
    Papa.parse("/drivencarstock.csv", {
      download: true,
      header: true,
        step: function(row) {
            //  push the row data into the array
            myRows.push(row.data);
        },
        complete: function() {
            //  upload using jQuery's AJAX
            $.ajax({
              url: '/path/on/your/server',
              method: 'post',
              data: myRows,
              success: function(response) {
                console.log('upload complete', response);
              },
              error: function() {
                console.error('an error occurred');
              }
            });
        }
    });
    

    Now, there are a couple of optimisations that could be made, such as posting the array every time it contains a fair amount of data and properly responding to the AJAX success/error callbacks, but this should get you going.