Open In App

How to Convert JSON Object to CSV in JavaScript ?

Last Updated : 19 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

JavaScript
// 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

  • In this approach we are using nodejs to convert the object into csv. We import the csvjson library, which provides functions for converting CSV data to JSON and vice versa.
  • We also import the built-in fs module, which allows us to interact with the file system in Node.js.
  • We use fs.readFile to read the JSON data from the file named data.json. The data is read asynchronously, and the callback function is executed when the file reading is complete or encounters an error.
  • Inside the callback function, we check for any errors that might have occurred during file reading. If there’s an error, we log it to the console and return.
  • If the file reading is successful, we proceed to convert the JSON data to CSV format using the csvjson.toCSV method. We pass the JSON data and specify that the headers should be derived from the keys of the JSON objects.
  • The resulting CSV data is stored in the csvData variable.
  • We use fs.writeFile to write the converted CSV data to a new file named output.csv. Similar to fs.readFile, this operation is asynchronous, and a callback function is provided to handle any errors that may occur during file writing.
  • If the file writing is successful, we log a success message to the console.

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

JavaScript
// 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.');
    });
});
JavaScript
// 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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads