While converting you CSV to JSON can be easy, converting JSON to CSV is definitely not an easy task.
JSON is not meant to be converted to CSV, as it is key-value pair based language where a value can be anything, it can be a simple string or it can be a complex object or it can be an array. While CSV is the complete opposite, its structure data in column and rows.
While converting JSON to CSV doesn’t make much sense, you can still get the business requirement to do so for the following reasons:
- JSON is not meant to be read by human eyes. CSV is easy to read and understand.
- Editing JSON is not easy and you can damage the JSON structure while editing it where CSV is very easy to edit.
- Reporting on JSON file is not easy, CSV is far better in reporting as it is structured data.
- JSON is meant for computers and programs, it works best when you use it inside your application, where it can be generated and parsed by the application itself, but if you need a JSON file as output to distribute to business users, it won’t make much sense.
I have tested above code with some complex JSON files, and I have got good results. You need to call getCSVString() methos and supply your JSON string. If you find that the code is not working as desired, please comment on this post with your question.