The Wayback Machine - https://web.archive.org/web/20240616194804/https://www.geeksforgeeks.org/how-to-convert-json-object-to-csv-in-javascript/
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



Similar Reads

How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to c
3 min read
How to Convert CSV to JSON in JavaScript ?
In this article, we will explain different ways to change Comma-Separated Values (CSV) data into JavaScript Object Notation (JSON) format, step-by-step. We'll break down each method with clear explanations and examples. There are several approaches available in JavaScript to convert CSV to JSON in JavaScript which are as follows: Table of Content S
3 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solve this problem, which are discussed below: Approach 1: Using JSON.parse() MethodThe basic method to convert JSON String to Array of JSON object
2 min read
Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to Convert JSON file into CSV in PHP ?
In this article, we are going to see how to convert JSON data into a CSV file using PHP. JSON (JavaScript Object Notation) is a dictionary-like notation that can be used to structuring data. It is stored with the extension .json, for example - geeksforgeeks.json On the other hand, CSV (or Comma Separated Value) files represent data in a tabular for
2 min read
How to Convert CSV to JSON in ReactJS ?
Dealing with data in various formats is a common task in web development. CSV (Comma Separated Values) and JSON (JavaScript Object Notation) are two widely used formats for storing and transmitting data. Converting CSV to JSON is often required when working with data in ReactJS applications. ApproachBegin by creating a new React application using t
4 min read
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
A CSV is a comma-separated value file, identified by the .csv extension, is a format used for tabular data storage where values are separated by commas. This article presents a method to convert CSV data to JavaScript Object Notation (JSON) without any relaying on third-party npm packages. Unlike typical conversions, this approach handles scenarios
4 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read