JSON and CSV are widely used formats for storing and exchanging data. Converting JSON to CSV makes structured data easier to export, analyze, and share.

- Data Conversion: Transforms JSON data into a tabular CSV format.
- Data Analysis: Supports spreadsheet-based analysis and reporting.
- Data Sharing: Simplifies data exchange between applications.
Convert JSON to CSV Using String Manipulation
This approach uses JavaScript methods such as Object.keys(), map(), and join() to extract headers and values and construct a CSV string.
const jsonData = [
{
id: 1,
name: "John Doe",
age: 30,
department: "Engineering"
},
{
id: 2,
name: "Jane Smith",
age: 28,
department: "Marketing"
}
];
function jsonToCsv(data) {
if (data.length === 0) {
return "";
}
const headers = Object.keys(data[0]);
const rows = data.map(obj =>
headers.map(header => obj[header] ?? "").join(",")
);
return [headers.join(","), ...rows].join("\n");
}
const csvData = jsonToCsv(jsonData);
console.log(csvData);
Output
id,name,age,department 1,John Doe,30,Engineering 2,Jane Smith,28,Marketing
Note: This basic implementation works for simple data. For production use, values containing commas, double quotes, or line breaks must be escaped according to CSV rules. It also assumes that all objects share the same keys.
Convert JSON to CSV Using the csvjson Library in Node.js
The csvjson library provides methods for converting JSON data to CSV and vice versa. In Node.js, you can combine it with the built-in fs module to read JSON data from a file and write the converted CSV data to another file.
Step 1: Install the library
npm install csvjsonStep 2: Create a data.json file
[
{
"id": 1,
"name": "John Doe",
"age": 30,
"department": "Engineering"
},
{
"id": 2,
"name": "Jane Smith",
"age": 28,
"department": "Marketing"
}
]
Step 3: Convert JSON to CSV
Create a convert.js file:
const csvjson = require("csvjson");
const fs = require("fs");
fs.readFile("data.json", "utf8", (err, fileContent) => {
if (err) {
console.error("Error reading JSON file:", err);
return;
}
try {
const jsonData = JSON.parse(fileContent);
const csvData = csvjson.toCSV(jsonData, {
headers: "key"
});
fs.writeFile("output.csv", csvData, "utf8", (err) => {
if (err) {
console.error("Error writing CSV file:", err);
return;
}
console.log("Conversion successful. CSV file created.");
});
} catch (error) {
console.error("Error parsing or converting JSON:", error);
}
});
Step 4: Run the program
node convert.jsOutput:
