Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

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]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

What is a straightforward way to convert a small CSV file without editing or replacing the original?

Geez

Read the CSV into memory, then write the result to a separate JSON path. Python’s csv.DictReader uses the header row as dictionary keys; its CSV fields are text values, not automatically inferred numbers or other types. [S1] The example below assumes your input is named input.csv, its first row contains headers, and it is UTF-8 encoded. Choose an output path that does not refer to the source file.

import csv
import json
from pathlib import Path

input_path = Path("input.csv")
output_path = Path("output.json")

if input_path.resolve() == output_path.resolve():
    raise ValueError("Choose a separate output path")

with input_path.open("r", newline="", encoding="utf-8") as csv_file:
    records = list(csv.DictReader(csv_file))

with output_path.open("w", encoding="utf-8") as json_file:
    json.dump(records, json_file, ensure_ascii=False, indent=2)

The input is opened for reading, and JSON is written to the separate output file. The Python tutorial documents json.dump for serializing a Python data structure to a text file and specifies UTF-8 for JSON files. [S2] This example assumes the CSV uses UTF-8; it does not detect the file’s encoding or determine whether its headers and values match your intended schema.

Follow-up question

How can I tell whether the conversion kept values like 007 or 12.50 unchanged?

Geez

Keep them as strings unless you deliberately define and validate a conversion rule. Since CSV fields are read as text, a value such as 007 remains text rather than being silently treated as a number. [S1] JSON represents strings with quotation marks, so "007" and "12.50" show that the original text form was retained.

For example, with this hypothetical CSV:

item,code,price
notebook,007,12.50

the corresponding JSON is:

[
  {
    "item": "notebook",
    "code": "007",
    "price": "12.50"
  }
]

That example demonstrates text preservation, not a rule about what the fields mean. If you need price to be numeric, decide what formats and values are valid first, then convert only that field using an explicit rule. Do not infer a type just because a value looks numeric.

Follow-up question

What can I check after writing the JSON, and how do I make sure the source was not used as the output?

Geez

Use separate input and output paths, then reopen the output as JSON and compare the parsed records with the in-memory records read from the CSV. This checks that the file can be parsed and that its loaded data matches what the script was about to write; it does not prove that the CSV’s contents are correct for your purposes.

Add this after the writing step:

with output_path.open("r", encoding="utf-8") as json_file:
    saved_records = json.load(json_file)

assert saved_records == records
print(f"Verified {len(saved_records)} records")

The earlier path check stops the script if the resolved input and output paths match. Keep the output path separate from the source file, and inspect the output as well, especially if the CSV has unusual formatting or empty fields. The sources establish the CSV reading and JSON writing approach, but not that this workflow will interpret every CSV layout or schema as intended. [S1] [S2]

Follow-up question

What should I change if I have a different filename or want to convert one field to a number?

Geez

Replace input.csv and output.json with your chosen paths, keeping them separate. If your CSV uses a different encoding, use the encoding you know applies rather than assuming UTF-8; the example’s encoding is an explicit assumption. Before converting a field, write down the rule—for example, which values are valid and what should happen to blanks or unexpected text—then check each value against that rule. The CSV reader does not perform type conversion automatically. [S1]

A practical order is to first produce and verify a text-preserving JSON file, then, if needed, add a narrow conversion for a named field and check it on representative records. Keep the original CSV unchanged and review the converted output for the cases your rule allows. The example does not infer missing-value meaning, validate a schema, or decide whether a numeric-looking value is an identifier.

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.DictReader and keep values as text unless a conversion rule is explicit.

  • Write JSON with json.dump to 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.

  1. [S1] Python csv module: reading CSV records
    docs.python.org · Checked
  2. [S2] Python tutorial: serializing structured data with JSON
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work