How to convert JSON to CSV in 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
Zsh

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' });
JavaScript

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 rn 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.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.