How to convert JSON to CSV in JavaScript

Josh Sherman
2 min read
Software Development Node.js JavaScript

Last week we discussed converting CSV to JSON in JavaScript. This week, we’re going to talk about going in the opposite direction, converting JSON back to CSV.

Similar to last week, we’re going to use the immensely popular papaparse library. As it turns out, even though it’s touted as the fastest CSV parser for JavaScript, it also supports “reverse parsing” back to JSON.

To get started, we’ll want to make sure we have papaparse installed via npm or yarn:

npm install --save papaparse
# or
yarn add papaparse

With the dependency added to our project, we can import or require it and get to converting.

In papaparse speak, converting from JSON to CSV is called “unparsing”. While I don’t love the naming, I do love that the dependency handles both quite well.

To unparse some JSON we can run:

const fs = require('fs');
const Papa = require('papaparse');

const jsonData = [
	{
		name: 'Jenny',
		website: 'http://thatgirljen.com',
		vlog: 'https://www.youtube.com/channel/UCMw00gabX-9jYq-SWDgij-w',
	},
	{
		name: 'Josh',
		website: 'http://joshtronic.com',
		vlog: null,
	},
];

const csvData = Papa.unparse(jsonData, { newline: '\n' });

With papaparse, converting from JSON to CSV is just as straight forward as going from CSV to JSON!

The newline option at the end is optional. If omitted, you’ll end up with lines ending with \r\n which may show up as ^M depending on your editor.

Also, I take back what I said about not liking the naming, now that I’ve played with it a bit more, I like the consistency of parse and then unparse to go in the opposite direction.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake (WE'RE HIRING!), and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Code Girls: The Untold Story of the American Women Code Breakers of World War II

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles