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. 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.

Data Engineer. Investor, blogger (https://fivestepguide.com) quadragenarian, father of 4 year old. I like to share knowledge & experience gained over 20+ years

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