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
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: 'https://thatgirljen.com',
vlog: 'https://www.youtube.com/channel/UCMw00gabX-9jYq-SWDgij-w',
},
{
name: 'Josh',
website: 'https://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.