CSV and JSON are commonly used formats for storing and exchanging structured data. CSV (Comma-Separated Values) stores data in rows and columns, while JSON (JavaScript Object Notation) stores data as objects containing key-value pairs.
In JavaScript, you can convert JSON data to CSV format and CSV data to JSON format using built-in methods without external libraries.
Converting JSON to CSV
To convert JSON data to CSV, we first define the column headers and then extract the corresponding values from each object. The headers and values are joined using commas, while each row is separated using a newline character.
Approach 1: Using Array Methods
In this approach, the join() method is used to create the CSV header and rows. The forEach() method iterates through each object and extracts the values corresponding to the specified keys.
Example: This example converts an array of JavaScript objects into CSV-formatted data.
<!DOCTYPE html>
<html>
<head>
<title>
Convert JSON to CSV in JavaScript
</title>
</head>
<body>
<script>
const JSONToCSV = (objArray, keys) => {
let csv = keys.join(",");
objArray.forEach(row => {
const 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>
</body>
</html>
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
Approach 2: Using map() Method
This approach provides a shorter way to convert JSON data to CSV. The map() method creates a CSV row for each object, while join() combines the rows using newline characters.
Example: This example converts an array of JavaScript objects into CSV data using map().
<!DOCTYPE html>
<html>
<head>
<title>
Convert JSON to CSV in JavaScript
</title>
</head>
<body>
<script>
const JSONToCSV = (objArray, keys) => [
keys.join(","),
...objArray.map(row =>
keys.map(key => row[key] ?? "")
.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>
</body>
</html>
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 CSV to JSON
To convert CSV data to JSON, we first extract the column names from the first row of the CSV data. These column names are then used as keys for creating JavaScript objects from the remaining rows.
Approach 3: Using split() and reduce() Methods
In this approach, the split() method separates the CSV data into rows and columns. The first row is used to create the object keys, while the reduce() method creates an object for each remaining row.
The trim() method is used to remove leading and trailing whitespace from the CSV data. This prevents empty lines from being interpreted as headers.
Example: This example converts CSV-formatted data into an array of JavaScript objects.
<!DOCTYPE html>
<html>
<head>
<title>
Convert CSV to JSON in JavaScript
</title>
</head>
<body>
<script>
const CSVToJSON = csv => {
const lines = csv.trim().split("\n");
const keys = lines[0]
.trim()
.split(",");
return lines.slice(1).map(line => {
const values = line.trim().split(",");
return keys.reduce(
(obj, key, index) => {
obj[key] = values[index];
return obj;
},
{}
);
});
};
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>
</body>
</html>
Output:
[
{
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"
}
]
Note: The trim() method removes leading and trailing whitespace from the CSV string. This prevents empty lines or extra spaces from being treated as CSV headers and ensures that the data is converted correctly.