CSV files to JSON

CSV files to JSON

Hey there, welcome, you are not comfortable with your data being in .csv format because

  • It can't present the data relationship very well merely looking at the data

  • It occupies high storage space

  • It is not so easy to work with at a high scale etc...

But you are told to use JSON as it takes away all the worries given to you by the CSV file. So here I will show you how you can convert your CSV file to a JSON file in Python.

CSV File

Screenshot (125).png

import json
import csv


def csv_to_json(csv_file_path, json_file_path):
    jsonArray = []
    #open the csv file
    with open(csv_file_path, encoding='utf-8') as csvfile:

        #Use csv file reader to read it

        csv_reader = csv.DictReader(csvfile)

        #convert and store the file into python dictionary

        for row in csv_reader:
            jsonArray.append(row)

        #write to a json file
        with open(json_file_path, 'w', encoding='utf-8') as jsonfile:
            jsonGotten = json.dumps(jsonArray, indent = 4)
            jsonfile.write(jsonGotten)

        return jsonGotten

result = csv_to_json('put csv file path', 'put json file path')

Result JSON File

Screenshot (126).png

Enjoy!!!