Try it yourself with our free Json To Csv tool — runs entirely in your browser, no signup needed.

How to Convert JSON to CSV in TypeScript

How to Convert JSON to CSV in TypeScript

Converting JSON data to CSV is a common requirement in data processing and analysis. JSON (JavaScript Object Notation) is a lightweight data interchange format, while CSV (Comma Separated Values) is a widely used format for tabular data. In this article, we will explore how to convert JSON to CSV in TypeScript, a superset of JavaScript that adds optional static typing and other features.

Quick Example

Here is a minimal example that converts a JSON object to a CSV string:

import * as fs from 'fs';
import * as json2csv from 'json2csv';

const jsonData = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Bob', age: 35 }
];

const csv = json2csv.parse(jsonData);
console.log(csv);
// Output:
// "name","age"
// "John","25"
// "Jane","30"
// "Bob","35"

This example uses the json2csv library, which can be installed using npm:

npm install json2csv

Step-by-Step Breakdown

Let's walk through the code line by line:

  • import * as fs from 'fs';: This line imports the built-in fs module, which provides functions for interacting with the file system. We don't actually use fs in this example, but it's included to demonstrate how to import modules in TypeScript.
  • import * as json2csv from 'json2csv';: This line imports the json2csv library, which provides a function for converting JSON data to CSV.
  • const jsonData = [...];: This line defines a JSON object containing an array of objects with name and age properties.
  • const csv = json2csv.parse(jsonData);: This line calls the parse function from json2csv to convert the JSON data to a CSV string.
  • console.log(csv);: This line logs the resulting CSV string to the console.

Handling Edge Cases

Here are some common edge cases to consider:

Empty/null input

If the input JSON data is empty or null, the json2csv library will throw an error. To handle this case, we can add a simple check:

if (!jsonData || jsonData.length === 0) {
  console.log('No data to convert');
} else {
  const csv = json2csv.parse(jsonData);
  console.log(csv);
}

Invalid input

If the input JSON data is invalid (e.g. not an array of objects), the json2csv library will throw an error. To handle this case, we can add a try-catch block:

try {
  const csv = json2csv.parse(jsonData);
  console.log(csv);
} catch (error) {
  console.error('Invalid input data');
}

Large input

If the input JSON data is very large, the json2csv library may throw an error or run out of memory. To handle this case, we can use a streaming approach:

import * as json2csv from 'json2csv';
import * as fs from 'fs';

const jsonData = [...]; // large JSON data

const csv = json2csv.parse(jsonData, { objectMode: true });
const writableStream = fs.createWriteStream('output.csv');

csv.pipe(writableStream);

This code uses the objectMode option to enable streaming, and pipes the output to a writable stream.

Unicode/special characters

If the input JSON data contains Unicode or special characters, the json2csv library may not handle them correctly. To handle this case, we can use the encoding option:

const csv = json2csv.parse(jsonData, { encoding: 'utf8' });

This code sets the encoding to UTF-8, which should handle most Unicode characters correctly.

Common Mistakes

Here are three common mistakes developers make when converting JSON to CSV in TypeScript:

Mistake 1: Forgetting to import the json2csv library

// WRONG
const csv = json2csv.parse(jsonData);

Corrected code:

import * as json2csv from 'json2csv';
const csv = json2csv.parse(jsonData);

Mistake 2: Not handling edge cases

// WRONG
const csv = json2csv.parse(jsonData);
console.log(csv);

Corrected code:

if (!jsonData || jsonData.length === 0) {
  console.log('No data to convert');
} else {
  try {
    const csv = json2csv.parse(jsonData);
    console.log(csv);
  } catch (error) {
    console.error('Invalid input data');
  }
}

Mistake 3: Not using the objectMode option for large input

// WRONG
const csv = json2csv.parse(jsonData);

Corrected code:

const csv = json2csv.parse(jsonData, { objectMode: true });
const writableStream = fs.createWriteStream('output.csv');
csv.pipe(writableStream);

Performance Tips

Here are three performance tips for converting JSON to CSV in TypeScript:

Tip 1: Use the objectMode option for large input

Using the objectMode option enables streaming, which can significantly improve performance for large input data.

Tip 2: Use a writable stream to output the CSV data

Instead of logging the CSV data to the console, use a writable stream to output it to a file. This can improve performance and avoid memory issues.

Tip 3: Use the encoding option to handle Unicode characters

Setting the encoding option to UTF-8 can improve performance and ensure that Unicode characters are handled correctly.

FAQ

Q: What is the best library for converting JSON to CSV in TypeScript?

A: The json2csv library is a popular and widely used library for converting JSON to CSV in TypeScript.

Q: How do I handle large input data when converting JSON to CSV?

A: Use the objectMode option to enable streaming, and pipe the output to a writable stream.

Q: How do I handle Unicode characters when converting JSON to CSV?

A: Use the encoding option to set the encoding to UTF-8.

Q: What is the difference between CSV and JSON?

A: CSV is a format for tabular data, while JSON is a format for hierarchical data.

Q: Can I use this code to convert JSON to CSV in JavaScript?

A: Yes, this code is written in TypeScript, but it can be easily converted to JavaScript by removing the type annotations.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp