How to Convert CSV to JSON file and vice-versa in JavaScript ?
Last Updated :
22 Apr, 2021
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 convert JavaScript objects JSON to the CSV file format and vice-versa. This code does not use any external libraries, and thus it works on both the browser and Node.js.
Converting From JSON To CSV
To convert from JSON to CSV, we first need to identify the headers of the CSV file. To do this, let's get a list of keys present in each of the JavaScript objects that has been passed in. To get this list of keys, use the `Object.keys()` method.
JavaScript
<script>
const JSONToCSV = (objArray, keys) => {
let csv = keys.join(',');
objArray.forEach((row) => {
let values = [];
keys.forEach((key) => {
values.push(row[key] || '');
});
csv += '\n' + values.join(',');
});
return csv;
};
const exampleJSON = [
{
"date": 20210307,
"positives": 28756184,
"fatalities": 515148
},
{
"date": 20210306,
"positives": 28714654,
"fatalities": 514309
},
{
"date": 20210305,
"positives": 28654639,
"fatalities": 512629
},
{
"date": 20210304,
"positives": 28585852,
"fatalities": 510408
},
{
"date": 20210303,
"positives": 28520365,
"fatalities": 508665
},
{
"date": 20210302,
"positives": 28453529,
"fatalities": 506216
},
{
"date": 20210301,
"positives": 28399281,
"fatalities": 504488
}
];
console.log(JSONToCSV(exampleJSON,
['date', 'positives', 'fatalities']));
</script>
This code can be simplified to:
JavaScript
<script>
const JSONToCSV = (objArray, keys) => [
keys.join(','), ...objArray.map(
row => keys.map(k => row[k] || '')
.join(','))].join('\n');
const exampleJSON = [
{
"date": 20210307,
"positives": 28756184,
"fatalities": 515148
},
{
"date": 20210306,
"positives": 28714654,
"fatalities": 514309
},
{
"date": 20210305,
"positives": 28654639,
"fatalities": 512629
},
{
"date": 20210304,
"positives": 28585852,
"fatalities": 510408
},
{
"date": 20210303,
"positives": 28520365,
"fatalities": 508665
},
{
"date": 20210302,
"positives": 28453529,
"fatalities": 506216
},
{
"date": 20210301,
"positives": 28399281,
"fatalities": 504488
}
];
console.log(JSONToCSV(exampleJSON,
['date', 'positives', 'fatalities']));
</script>
Output:
date, positives, fatalities
20210307, 28756184, 515148
20210306, 28714654, 514309
20210305, 28654639, 512629
20210304, 28585852, 510408
20210303, 28520365, 508665
20210302, 28453529, 506216
20210301, 28399281, 504488
Converting From CSV To JSON
To convert from CSV to JSON, first identify a list of keys for each JavaScript object by parsing the CSV headers, then add each key and value to a new object for each CSV row.
JavaScript
<script>
const CSVToJSON = csv => {
const lines = csv.split('\n');
const keys = lines[0].split(',');
return lines.slice(1).map(line => {
return line.split(',').reduce((acc, cur, i) => {
const toAdd = {};
toAdd[keys[i]] = cur;
return { ...acc, ...toAdd };
}, {});
});
};
const exampleCSV = `
date,positives,fatalities
20210307,28756184,515148
20210306,28714654,514309
20210305,28654639,512629
20210304,28585852,510408
20210303,28520365,508665
20210302,28453529,506216
20210301,28399281,504488`;
console.log(CSVToJSON(exampleCSV));
</script>
Output:
Similar Reads
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 J
3 min read
How to Convert JSON to Excel in JavaScript? It is often necessary to export or download JSON data in the form of Excel spreadsheets when developing web applications, any web developer would be able to go through this article as it provides a useful function of converting JSON files to Excel format using SheetsJS through JavaScript.These are t
4 min read
How to Convert Excel to JSON in JavaScript ? Converting Excel spreadsheets to JSON format is a common requirement in various applications. JavaScript code utilizes the read-excel-file library to parse the Excel data, convert it to JSON format, and display it. Additionally, it provides functionality to download the generated JSON file. Approach
3 min read
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 Conte
3 min read
How to Convert XML to JSON in JavaScript? To convert XML to JSON in JavaScript, various methods and libraries and be used. Here, we use xml-js library that provides xml2json function to convert XML to JSON data. It takes XML data as input and gives the JSON objects as output. We can also use the DOMParser from the xmldom package to convert
2 min read