Convert each row in a CSV to a separate JSON file using Python
I searched the internet for a simple solution to my problem of converting a CSV to JSON. I found many sites and blogs posting simple python or Perl code to convert CSV to JSON. All of them were simple and worked well except that all had the basic item missing. My requirement was to convert each row in my CSV to a separate JSON file to be added to Mongo DB as part of the larger project I am working on.
Since I couldn’t find any solution, i decided to make my own in python
- 1. Open the CSV file and read the contents in a variable using DictReader() function — this function returns an OrderedDict.
2. For every row in CSV presented by this OrderedDict, create a new JSON file using json.dumps() and write functions. Note: There is indentation below for loop.
3. Close the streams
This will create as many JSON files as number of rows in the CSV.
Hope this helped.