How can I convert a small CSV file to JSON without changing the source?
Quick answer
Use Python’s csv.DictReader to read the CSV into dictionaries, then write those records with json.dump to a different output file. CSV fields are read as text, so values such as 007 stay strings unless you explicitly convert them. Reopen the JSON file and compare its parsed contents with the records you read. Keep the input and output paths separate, and use UTF-8 for the JSON file. [S1] [S2]
The question, the details, the next step.
A practical checklist
Confirm the CSV has a header row and choose the correct input encoding.
Set different input and output paths; do not open the CSV path for writing.
Read rows with
csv.DictReaderand keep values as text unless a conversion rule is explicit.Write JSON with
json.dumpto a UTF-8 text file at the separate output path.Reopen the JSON, parse it, and compare the result with the records read from the CSV.
Review representative output values, including identifiers with leading zeros and blank fields.
A few more useful answers
Will CSV values that look numeric automatically become JSON numbers?
No. DictReader returns CSV fields as text; conversion to numbers is not automatic. [S1] Convert a field only under a deliberate rule that checks valid values.
Does the output have to be UTF-8?
The Python tutorial specifies UTF-8 for JSON files, so the example opens the output with encoding="utf-8". [S2] The example assumes the input CSV is also UTF-8.
Does comparing the saved JSON with the records validate the CSV itself?
No. It checks that the saved JSON parses and matches the records the script read. It does not confirm that the source data, headers, or interpretation meet your intended requirements.
Sources
References used for this guide.
- [S1] Python csv module: reading CSV records docs.python.org · Checked
- [S2] Python tutorial: serializing structured data with JSON docs.python.org · Checked
