← all snippets

csv-to-json

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.

Python 3 #04

Source

csv-to-json.py
#!/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))

Input

path.csvstring — positional argument, path to a CSV file with a header row, e.g. users.csv

Output

Prints a JSON array to stdout, one object per data row, keys taken from the first (header) row, all values as strings. Exits non-zero with a message if the file can't be opened.

Usage

$ cat users.csv
name,role
Ada,architect
Grace,engineer

$ python3 csv-to-json.py users.csv
[
  {
    "name": "Ada",
    "role": "architect"
  },
  {
    "name": "Grace",
    "role": "engineer"
  }
]

Config

No configuration required.

Security notes

  • Uses the standard csv module's DictReader instead of hand-rolled comma splitting, which correctly handles quoting and embedded commas.
  • File is opened with an explicit UTF-8 encoding to avoid silently mis-decoding data.