Delimited data conversion
Convert CSV Data to JSON in Python with Header Validation
Convert CSV Data to JSON in Python with Header Validation. Preserve field values with explicit parsing, encoding and a checked output round trip.
Use Python’s csv.DictReader to map named CSV columns to JSON object keys, then write the resulting list with json.dump. Decide the schema first: this example preserves every CSV value as a string, including leading-zero identifiers and empty cells. It does not guess numbers, dates or null values.
Validate the header before building objects
JSON object keys need an unambiguous mapping from columns. Empty or duplicate CSV headers can lose that meaning. The example rejects both, and it rejects rows with more or fewer fields than the header instead of silently discarding or inventing values.
For a source header id,name,note and a row with 00123, Lee, Ana as a quoted name, and an empty note, expect an object whose id is the string 00123 and whose note is the empty string. A JSON numeric value of 123 would be a deliberate type conversion, not the same interchange contract.
Convert types only under an explicit schema
If quantity must be an integer, convert that named field and reject invalid values. Do not apply numeric conversion to every digit-only string; account codes and postal codes can be identifiers. Similarly, distinguish a blank string from a missing value before introducing JSON null.
Nested JSON objects do not appear automatically because a CSV header contains a dot. Decide whether a name such as address.city is a literal key or a path into an object. Use a documented mapping and test it separately if the receiving API expects a nested structure.
Know the memory boundary
This small example loads the parsed records into a list before writing a JSON array. For a large source, use a tested streaming array writer or newline-delimited JSON if the receiver explicitly accepts that different format. A collection of separate JSON objects on new lines is not the same file format as one JSON array.
Count parsed records rather than physical lines because quoted CSV values can contain embedded newlines. After conversion, reopen the JSON and verify object count, expected keys and representative values. Keep the original CSV available until the receiving system accepts the intended schema.
Executable conversion example
import csv, json
with open("input.csv", encoding="utf-8-sig", newline="") as source:
reader = csv.DictReader(source, strict=True)
fields = reader.fieldnames
if not fields or any(not field for field in fields):
raise ValueError("Expected nonempty column names")
if len(set(fields)) != len(fields):
raise ValueError("Duplicate column names are ambiguous")
rows = list(reader)
if any(None in row or any(value is None for value in row.values())
for row in rows):
raise ValueError("Record width does not match the header")
with open("output.json", "w", encoding="utf-8") as target:
json.dump(rows, target, ensure_ascii=False, indent=2)
with open("output.json", encoding="utf-8") as check:
assert json.load(check) == rows
Use a representative acceptance fixture
Begin with two different data records containing a leading-zero identifier, an embedded comma, a quotation mark, an empty field and a non-ASCII name when the destination supports it. Read the output with a parser for the destination format and compare the actual values, column order and record count. A save message or familiar extension does not establish that the records survived correctly.
Change the second fixture’s values rather than rerunning only the same sample. Include a malformed record and confirm that the conversion reports it instead of producing a misleading success. Keep the original unchanged and write the result to a separate path. Avoid exposing sensitive source values in public error logs.
Choose the format-aware operation
The Convert Text to CSV tool here works with already extracted plain text. It does not infer every structured file format or replace the Python parsers shown above. Use the operation whose input contract matches the actual source, and verify the result independently before importing it into another application.
Python reference
Python’s CSV module documentation explains the parser and writer dialect options. The published snippets and acceptance cases in this family are executed locally against disposable fixtures.


