Batteries included
: turning CSV into JSON in Python
Say you’ve got a CSV file with many rows, and what you want is a directory of JSON files, one per row.
I’ve found myself needing to do this a couple times , and this sort of thing is super easy to do using the csv and json modules in Python’s standard library, so I thought I’d write it up here.
with open("example.csv", encoding='utf-8') as infile:
for row in csv.DictReader(infile):
with open(filename(row), mode='w', encoding='utf-8') as outfile:
json.dump(row, outfile, indent=4)
That’s it! I love how close this snippet is to a pseudo-code sketch of the solution—one of the side-effects of Python’s batteries included
philosophy.
Strictly speaking, the above snippet needs two additional pieces to work. First, you need to import the csv and json modules from the standard library. Second, you need to write some code that generates an appropriate filename from a row of data.
csv-to-json.py#!/usr/bin/env python3
import csv
import json
def filename(row):
...
Convert CSV to JSON