convert json to csv in typescript

To convert JSON to CSV in TypeScript, we need to read the data from a JSON file, transform the data into a CSV format, and write it to a CSV file. We will be using the fs module to read and write files.

Here is an example TypeScript code to convert JSON to CSV:

index.ts
import * as fs from 'fs';

interface Data {
  [key: string]: any;
}

const jsonToCsv = (json: Data[]) => {
  const headers = Object.keys(json[0]);

  const csvRows = [];
  csvRows.push(headers.join(','));

  for (const item of json) {
    const values = headers.map(header => {
      const cellValue = item[header];
      if (typeof cellValue === 'string') {
        return `"${cellValue}"`;
      } else {
        return cellValue;
      }
    });
    csvRows.push(values.join(','));
  }

  return csvRows.join('\n');
};

const jsonFilePath = 'data.json';
const csvFilePath = 'data.csv';

const jsonData = JSON.parse(fs.readFileSync(jsonFilePath, 'utf8'));
const csvData = jsonToCsv(jsonData);

fs.writeFileSync(csvFilePath, csvData);
736 chars
35 lines

In this example, we define an interface Data to represent the shape of each JSON object. We define a function jsonToCsv that takes an array of JSON objects as input and returns a string of CSV data. The function first extracts the headers from the keys of the first JSON object. It then iterates over each JSON object and extracts the corresponding values for each header, formatting the values as necessary according to the rules of CSV. Finally, the function returns a string of CSV data.

We read the JSON data from a file using fs.readFileSync. We then pass the JSON data to the jsonToCsv function to get the CSV data. Finally, we write the CSV data to a file using fs.writeFileSync.

Note that this code assumes that the JSON data is an array of objects with consistent keys. If the JSON data is not consistent, you may need to modify the code to handle the differences.

gistlibby LogSnag