In this section, we describe a variety of ways to manipulate CSV into JSON, and vice versa, using Python. In these examples, we will explore different ways to accomplish this goal, both using specially installed libraries and using more plain-vanilla Python code.
We have found several ways to convert CSV files to JSON using Python. The first of these uses the built-in csv
and json
libraries. Suppose we have a CSV file that has rows like this (only the first three rows shown):
name,email_id "Lysa Akin",[email protected] "Phillip Allen",[email protected] "Harry Arora",[email protected]
We can write a Python program to read these rows and convert them to JSON:
import json import csv # read in the CSV file with open('enronEmail.csv') as file: file_csv = csv.DictReader(file) output = '[' # process each dictionary row for row in file_csv: # put a comma between the entities output += json.dumps(row) + ',' output...