A long time ago (I’m slightly embarrassed to admit) I mentioned that I wrote a script to flatten JSON to CSV and I promised to share it. I didn’t fulfill this promise till today. The reason being that the script was very rough and I wanted to sharpen it before letting it loose on the interwebs. I still didn’t get around to properly clean it up and probably will not for a couple more months or more. However, I decided today to release it as is. I’m sure some will find it useful enough and maybe be willing to tidy some of it up.
So here’s the story. There are plenty of tools out there to convert from CSV to JSON; e.g. Mr. Data Converter, CSV to JSON, csv2couch. However, converting from JSON, a flexible self-describing format, to CSV, a much more rigid format, is not as simple. I found some attempts (like jackson-dataformat-csv) but these require a predefined schema. This did not really suit my needs as I do not want to define a schema for each JSON file I need to convert. I just know that I have a JSON with a reliably consistent structure and I want to convert it to CSV/TSV for another program that can only accept such format.
So I developed my code with such requirements in mind. So be careful: inconsistent JSON structure will result in wrong CSV. The code parses the JSON twice: once to discover the schema, and again to convert.
Here it is. Enjoy, and be gentle 🙂