How to Convert JSON Object to CSV in JavaScript ? Last Updated : 19 Apr, 2024 Summarize Comments Improve Suggest changes Share Like Article Like 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: Table of Content Using String ManipulationUsing csvjson library in nodeJsUsing String ManipulationThis 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); Outputid,name,age,department 1,John Doe,30,Engineering 2,Jane Smith,28,MarketingUsing csvjson library in nodeJsIn 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. Comment More infoAdvertise with us Next Article How to Convert JSON Object to CSV in JavaScript ? L lunatic1 Follow Improve Article Tags : JavaScript Web Technologies JSON Similar Reads Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav 11 min read Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De 5 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications 15+ min read React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version 7 min read JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q 15+ min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read 3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power 13 min read Like