简体   繁体   中英

Export Json data to Plain Text using Pure Javascript

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

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(',') + "*"
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM