Code Examples

Convert CSV to JSON


The following code, in Python, takes 2 file paths as parameters: your source CSV file and your destination JSON file, which will be created.

import csv
import json

def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []

    #read csv file
    with open(csvFilePath, encoding='utf-8') as csvf:
        #load csv file data using csv library's dictionary reader
        csvReader = csv.DictReader(csvf)

        #convert each csv row into python dict
        for row in csvReader:
            #add this python dict to json array

    #convert python jsonArray to JSON String and write to file
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonString = json.dumps(jsonArray, indent=4)

# function call
csvFilePath = r'input.csv'
jsonFilePath = r'output.json'
csv_to_json(csvFilePath, jsonFilePath)