0

I'm using the following to download a file created with JavaScript in a vue project on the client side that also uses json2csv.

      // console.log('wtf all 200 rows are here!', modifiedData);

      const csv = json2csvParser.parse(modifiedData);
      let content = 'data:text/csv;charset=utf-8,';
      content += csv;
      const data = encodeURI(content);
      const link = document.createElement('a');
      link.setAttribute('href', data);
      link.setAttribute('download', 'errors_totalcost.csv');
      link.click();

But for some reason the file only has 29 rows instead of all 200. The above code doesn't work at all in firefox, but use to work in chrome, now it's broken in chrome and truncates the file.

Can anybody explain what is wrong and how to resolve it while still creating file on client side?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
jtlindsey
  • 4,346
  • 4
  • 45
  • 73

1 Answers1

0

One of the fields (row 28) was a note field containing text that looked like the following when rendered in browser:

Sale Numbers:
#1453
#142356
#78527
#4563232
#45378
#675675
#32452

Or in object like:

{t:"Sale Numbers:↵#1453↵#142356↵#78527↵#4563232↵#45378↵#675675↵#32452"}

I don't know why but chrome stopped processing after that row. It looks like it's due to the # and the fix is to replace it. You can reproduce with the following:

const json2csvParser = new Json2csvParser();

const fakeObj = []

for (let index = 0; index < 100; index++) {
  fakeObj.push({
    a:4, b:2, c:1, v:7, t:23, s:10
  })        
};
fakeObj.push({
  a:4, b:2, c:1, v:7, 
  t:"Sale Numbers:↵#1453↵#142356↵#78527↵#4563232↵#45378↵#675675↵#32452", // will cause issue
  // t: "Sale Numbers:↵#1453↵#142356↵#78527↵#4563232↵#45378↵#675675↵#32452".replace(/(#)/gm, " "), // this solution works
  s:10
})
fakeObj.push({
  a:"you wont get this row if the one before has a hash", b:2, c:1, v:7, t:"", s:10
})      

const csv = json2csvParser.parse(fakeObj);
let content = 'data:text/csv;charset=utf-8,';
content += csv;
const data = encodeURI(content);
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', 'errors_totalcost.csv');
link.click();
jtlindsey
  • 4,346
  • 4
  • 45
  • 73