Skip to content

Instantly share code, notes, and snippets.

@qwerty13
Created June 8, 2023 07:15
Show Gist options
  • Save qwerty13/350260d862da637f9d8bb6bc7c68494c to your computer and use it in GitHub Desktop.
Save qwerty13/350260d862da637f9d8bb6bc7c68494c to your computer and use it in GitHub Desktop.
Python CSV To JSON Converter (Each column in one array)
from collections import defaultdict
import csv
import json
def csv_to_json(csvFilePath, jsonFilePath):
# Make Dictionary with default "List"
jsonArray = defaultdict(list)
#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:
for i in range(len(row)):
jsonArray[list(row.keys())[i]].append(list(row.values())[i])
# 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)
jsonf.write(jsonString)
# Test
csvFilePath = r'data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment