Home > Software design >  Export Json data to Plain Text using Pure Javascript
Export Json data to Plain Text using Pure Javascript

Time:11-03

I have Javascript Function that export json to txt file

function download() {
      const originalData = [
        {
          name: 'Support',
          message: 'Hey! Welcome to support',
        },
        {
          name: 'Me',
          message: 'Hello there!',
        },
        {
          name: 'Support',
          message: 'What can I do for you?',
        },
      ];

      var items = originalData;
      const replacer = (key, value) => (value === null ? '' : value); // specify how you want to handle null values here
      const header = Object.keys(items[0]);
      let csv = items.map((row) =>
        header
          .map((fieldName) => JSON.stringify(row[fieldName], replacer))
          .join(',')
      );
      csv.unshift(header.join(','));
      csv = csv.join('\r\n');

      //Download the file as CSV/TXT just change the extension
      var downloadLink = document.createElement('a');
      var blob = new Blob(['\ufeff', csv]);
      var url = URL.createObjectURL(blob);
      downloadLink.href = url;
      downloadLink.download = 'DataDump.txt'; //Name the file here
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    }

result is

name,message
"Support","Hey! Welcome to support"
"Me","Hello there!"
"Support","What can I do for you?"

Expected Value that i want is like this, there is include '*' in every last string on row > 1

name,message
"Support","Hey! Welcome to support"*
"Me","Hello there!"*
"Support","What can I do for you?"*

How To add '*' on line > 1 or row > 1

CodePudding user response:

The easiest would probably be, just to add the * when you create the lines of your CSV

let csv = items.map((row) =>
    header
      .map((fieldName) => JSON.stringify(row[fieldName], replacer))
      .join(',')   "*"
  );
  • Related