Open In App

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:

Using String Manipulation

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

Using csvjson library in nodeJs

Example: This example shows the implementation of the above-explained approach.

// convert.js
const csvjson = require('csvjson');
const fs = require('fs');

// Read JSON data from file
fs.readFile('data.json', 'utf-8', (err, fileContent) => {
    if (err) {
        console.error(err);
        return;
    }

    // Convert JSON to CSV
    const csvData = csvjson.toCSV(fileContent, {
        headers: 'key'
    });

    // Write CSV data to file
    fs.writeFile('output.csv', csvData, 'utf-8', (err) => {
        if (err) {
            console.error(err);
            return;
        }
        console.log('Conversion successful. CSV file created.');
    });
});
// data.json
[
    {
        "id": 1,
        "name": "John Doe",
        "age": 30,
        "department": "Engineering"
    },
    {
        "id": 2,
        "name": "Jane Smith",
        "age": 28,
        "department": "Marketing"
    },
    {
        "id": 3,
        "name": "Michael Johnson",
        "age": 35,
        "department": "Human Resources"
    },
    {
        "id": 4,
        "name": "Emily Davis",
        "age": 32,
        "department": "Finance"
    },
    {
        "id": 5,
        "name": "Alex Brown",
        "age": 27,
        "department": "Sales"
    }
]

Output: An output.csv file will be generated after running the code.

Screenshot-2024-04-05-193016

Screenshot-2024-04-05-193147

Article Tags :