JavaScript

How to Convert JSON to CSV Format and Store in a Variable

While working with JSON data in JavaScript, developers might need to convert this data into multiple formats. One of the common converting formats is JSON to CSV. It is a common data processing and analysis operation. CSV also known as “Comma Separated Values” is a common configuration for storing and transferring tabular data that can be efficiently imported into spreadsheet apps such as “Microsoft Excel” or “Google Sheets”.

This article will describe the ways for converting the JSON to CSV format and storing it in a variable.

How to Convert JSON to CSV Format and Store in a Variable?

For converting JSON data to CSV format, the following approaches are used:

Method 1: Convert JSON to CSV Format and Store in a Variable Using “join()” Method

For converting JSON data to CSV format, first, use the “JSON.parse()” method that will convert the JSON string into an object. Then, call the “Object.keys()” method to retrieve the keys of an object in an array that will be the header of the CSV file. After retrieving keys, invoke the “join()” method on the array to concatenate/join all the elements into a CSV header string. Then, call the “map()” method of an “Array” object for getting the property values from each object.

Example

Create a variable “jsonData” that stores a JSON string/data:

const jsonData = '[{"id": 1, "name": "Jerry", "age": 25}, {"id": 2, "name": "Joseph", "age": 27}, {"id": 3, "name": "John", "age": 27}]';

 
Convert the JSON string into an Object using the “JSON.parse()” method:

const parsedData = JSON.parse(jsonData);

 
Retrieve all the keys using the “Object.keys()” method:

const jsonKeys = Object.keys(parsedData[0]);

 
Invoke the “join()” method to join the keys with a comma into a CSV header:

const headerData = jsonKeys.join(',');

 
Now, map the values against each key using the “map()” method and join them as comma-separated values using the “join()” method:

const rowData = parsedData.map((item) => {
 return jsonKeys.map((key) => item[key]).join(',');
});

 
Separate the header string with the values against keys with the help of “\n” character:

const json2CSV = `${headerData}\n${rowData.join('\n')}`;

 
Finally, print the CSV formatted data on the console using the “console.log()” method:

console.log(json2CSV);

 
The output indicates that the JSON data has been successfully converted into CSV format:

Method 2: Convert JSON to CSV Format and Store in a Variable Using “for” Loop

Another way for converting the JSON data to CSV format, use the “for” loop with “JSON.parse()” method. In this approach, we will get the keys and map the values against keys using the “for” loop instead of using the JavaScript prebuilt methods “Object.keys()” and the “map()” method.

Example

After parsing JSON string to an object, create an empty array for collecting keys:

const jsonKeys = [];

 
Use the “for” loop with the “push()” method to add the keys in an array:

for (const key in parsedData[0]) {
 jsonKeys.push(key);
}

 
Call the join() method to join the keys as a CSV header string and set the cursor to the next line for adding values:

var json2CSV = jsonKeys.join(',') + '\n';

 
Now, map the values against keys using the “for” loop:

for (var i = 0; i < parsedData.length; i++) {
 var row = '';
 for (const key of jsonKeys) {
  if (row !== '') {
   row += ',';
  }
  row += parsedData[i][key];
 }
 json2CSV += row + '\n';
}

 
Lastly, display the CSV formatted data on the console:

console.log(json2CSV);

 
Output


We have compiled all the essential information related to the conversion of JSON data into CSV format and stored it in a variable in JavaScript.

Conclusion

Use the “join()” method with the “map()” method or traditional “for” loop to convert JSON to CSV format and store it in a variable. “join()” method with the “map()” method is the simple and quick approach for the conversion of JSON data into CSV format. This article described the ways for converting the JSON to CSV format and storing it in a variable.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.