JSON to CSV Converter in JavaScript

or a simple example to use functional programming in JavaScript

Image for post
Image for post

Today I wanted to paste my JSON into a Spreadsheet like Excel, but that was a mess. It could not get along with it and hence it is no fun to do this by hand, I implemented a small tool to do this for me.

The input was this test.json — almost, I have created an object of it:

The interesting thing is, that the data is nested and not only on one level. What I want in result was this test.xlsx:

Image for post
Image for post

It shows the nested structure of the JSON file using more columns. I have done this by creating this JSON to CSV Converter that creates me a CSV that I can import very easy.


It is called with node to-csv.js > test.csv and gives me the


That can be imported into almost each spreadsheet, I think.

The programm lacks the support of an input file, you have to define a const data variable with the json to use it — see the source above.

So how it is implemented?

First I have to calculcate the max horizontal depth of the spreadsheet, how many columns it needs. So I have to traverse through the whole document and count the depth.

The next step is to create the data for the CSV. Again I have to traverse the data structure. So it makes sense to create a method that can traverse a JSON structure using recursion. I named it traverse.

It takes the data and a callback to be called during traversion.

For the calculation of the depth the callback is simply used to compare the actual depth to the actual max depth.

After this, I have calculated the max depth for the data.

It remains the next step, creating the CSV output. Therefore I put another function into the call of traverse.

This function calculates the semicolons to prefix and the indent semicolons for the current key and value. And only primitive values should be written in the value column, Array and Object will be ignored.

And that’s it.

See you

Developer since the 80'th, working at Forschungszentrum Jülich (http://www.fz-juelich.de) …

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store