← Runnable Projects

阅读中文版本

CSV to JSON Converter in Python

A standard-library CLI that converts a CSV file with headers into a JSON array and reports the number of rows converted.

beginnerpythonverified-runnable

Project

python-csv-to-json

Entry point: csv_to_json.py

Install

python --version

Run

python csv_to_json.py sample.csv out.json

Test

python csv_to_json.py sample.csv out.json

Expected output

Prints "converted 2 rows" and writes a JSON array with two objects to out.json.

Dependencies

  • python >=3.10

Verification evidence

Python 3.11.7: converted a 2-row CSV; out.json contained two objects with name and age fields and printed "converted 2 rows".

Security note

Treats CSV values as strings and does not sanitize output for downstream HTML; consumers must encode values appropriately.

What it does

Reads a CSV file with a header row and writes a JSON array. It uses only csv, json, and argparse from the standard library.

import argparse
import csv
import json


def convert(input_path: str, output_path: str) -> int:
    with open(input_path, newline="", encoding="utf-8") as source:
        rows = list(csv.DictReader(source))
    with open(output_path, "w", encoding="utf-8") as target:
        json.dump(rows, target, indent=2)
        target.write("\n")
    return len(rows)


def main() -> None:
    parser = argparse.ArgumentParser(description="Convert CSV to JSON")
    parser.add_argument("input")
    parser.add_argument("output")
    args = parser.parse_args()
    count = convert(args.input, args.output)
    print(f"converted {count} rows")


if __name__ == "__main__":
    main()

Run and verify

printf 'name,age\nAlice,30\nBob,41\n' > sample.csv
python csv_to_json.py sample.csv out.json
cat out.json

Expected output starts with converted 2 rows, and out.json contains an array of two objects. The converter preserves CSV values as strings. Verified with Python 3.11.7: the conversion test passed and produced the expected file.

Limitations

Reads the whole file into memory and does not infer numeric or boolean types. For very large CSVs, stream rows and write JSON incrementally; for typed output, define an explicit schema.