Converts a CSV file into a JSON array of objects, one per row, keyed by the header row. Handy for feeding a spreadsheet export into a script or API.
#!/usr/bin/env python3
"""Convert a CSV file to a JSON array of objects."""
import csv
import json
import sys
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("usage: csv-to-json.py <path.csv>")
try:
with open(sys.argv[1], newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
except OSError as e:
sys.exit(f"error: {e}")
print(json.dumps(rows, indent=2, ensure_ascii=False))
| path.csv | string — positional argument, path to a CSV file with a header row, e.g. users.csv |
|---|
$ cat users.csv
name,role
Ada,architect
Grace,engineer
$ python3 csv-to-json.py users.csv
[
{
"name": "Ada",
"role": "architect"
},
{
"name": "Grace",
"role": "engineer"
}
]
csv module's DictReader instead of hand-rolled comma splitting, which correctly handles quoting and embedded commas.