How to use String Manipulation In Javascript
This approach involves manually iterating through the JSON object and constructing the CSV string by concatenating values with commas and newline characters.
Example: This example shows the conversion of json object to csv using string manipulation.
// JSON data
const jsonData = [
{
"id": 1,
"name": "John Doe",
"age": 30,
"department": "Engineering"
},
{
"id": 2,
"name": "Jane Smith",
"age": 28,
"department": "Marketing"
}
];
// Convert JSON to CSV manually
function jsonToCsv(jsonData) {
let csv = '';
// Extract headers
const headers = Object.keys(jsonData[0]);
csv += headers.join(',') + '\n';
// Extract values
jsonData.forEach(obj => {
const values = headers.map(header => obj[header]);
csv += values.join(',') + '\n';
});
return csv;
}
// Convert JSON to CSV
const csvData = jsonToCsv(jsonData);
console.log(csvData);
Output
id,name,age,department 1,John Doe,30,Engineering 2,Jane Smith,28,Marketing
How to Convert JSON Object to CSV in JavaScript ?
JSON (JavaScript Object Notation) and CSV (Comma-Separated Values) are two widely used formats, each with its own strengths and applications. Fortunately, JavaScript provides powerful tools to facilitate the conversion process between these formats.
These are the following approaches:
Table of Content
- Using String Manipulation
- Using csvjson library in nodeJs