Validate CSV headers and row widths before importing records
Python
Convert a small CSV document to records under an explicit strict policy.
Convert a small CSV document to records under an explicit strict policy. This stdin-based Python CLI processes one bounded JSON request and returns the documented JSON result. It does not execute jobs or contact external services. Inspect its limits before adapting it to an application.
Before you start
Python 3.12 standard library; no third-party packages. Verified with the recorded pinned runtime.
One UTF-8 JSON object on stdin, no command-line arguments. Maximum encoded request size is 20000 bytes.
Build and check
Save the source as validate-csv-records-python.py.
Save the example JSON below as request.json.
Run python3 validate-csv-records-python.py < request.json.
Compare the parsed JSON result with the expected output. Invalid input exits 2 with empty stdout and a generic stderr message.
Limits to understand
Spreadsheet formula injection protection is outside scope; formula-like field values are preserved and never executed by this program.
Schema validation beyond the required input shape, header constraints, row widths, and row limit is outside scope.
CSV syntax follows Python's csv.reader with strict=True, comma delimiters, and double-quote quoting; formats are not sniffed.
Input exactly {"text":string}. Use Python csv.reader on io.StringIO(text,newline=""), delimiter comma, quotechar double quote, strict=True. Do not sniff formats or trim fields.
First parsed row is the header. Require 1..50 distinct nonempty header strings. Every subsequent row, including a blank row, must have exactly that width. Allow at most 500 data rows.
Output {"headers":array,"records":array of objects with string field values}. Reject empty document, malformed quoting, duplicate headers or width mismatch.
Do not execute formulas or coerce types. Document that spreadsheet formula injection protection and schema validation are outside scope.
The complete encoded input is limited to 20000 bytes; one additional byte can be read to detect overflow.
This is a bounded local helper. Passing the recorded cases does not verify every input, every Python version or an external integration.
This browser preview builds code locally. It does not contact an API or run the code.
Default example ready.
Python example
import csv
import io
import json
import math
import sys
def reject_constant(_value):
raise ValueError('invalid JSON constant')
def finite_float(value):
result = float(value)
if not math.isfinite(result):
raise ValueError('non-finite number')
return result
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError('duplicate key')
result[key] = value
return result
def validate_unicode(value):
if isinstance(value, str):
if any(0xD800 <= ord(char) <= 0xDFFF for char in value):
raise ValueError('unpaired surrogate')
elif isinstance(value, dict):
for key, item in value.items():
validate_unicode(key)
validate_unicode(item)
elif isinstance(value, list):
for item in value:
validate_unicode(item)
def convert():
if len(sys.argv) != 1:
raise ValueError('arguments not allowed')
raw = sys.stdin.buffer.read(20001)
if len(raw) > 20000:
raise ValueError('input too large')
document = json.loads(
raw.decode('utf-8', errors='strict'),
object_pairs_hook=unique_object,
parse_float=finite_float,
parse_constant=reject_constant,
)
validate_unicode(document)
if not isinstance(document, dict) or set(document) != {'text'}:
raise ValueError('invalid input shape')
if not isinstance(document['text'], str):
raise ValueError('text must be a string')
reader = csv.reader(
io.StringIO(document['text'], newline=''),
delimiter=',',
quotechar='"',
strict=True,
)
headers = next(reader, None)
if headers is None or not 1 <= len(headers) <= 50:
raise ValueError('invalid header width')
if any(header == '' for header in headers):
raise ValueError('empty header')
if len(set(headers)) != len(headers):
raise ValueError('duplicate headers')
records = []
for row in reader:
if len(records) >= 500:
raise ValueError('too many rows')
if len(row) != len(headers):
raise ValueError('row width mismatch')
records.append(dict(zip(headers, row)))
return json.dumps(
{'headers': headers, 'records': records},
ensure_ascii=True,
allow_nan=False,
separators=(',', ':'),
)
def main():
try:
output = convert()
except Exception:
sys.stderr.write('Invalid input\n')
return 2
sys.stdout.write(output + '\n')
return 0
if __name__ == '__main__':
sys.exit(main())
What to verify after running
Run the documented example and compare the JSON result.
Confirm malformed requests exit 2 without copying input data into diagnostic messages.
24 independent CLI cases passed on this exact source, including an unexpected-argument check.
Request or format preview
Illustrative preview. No provider response, price or balance is fetched.
Code license: MIT. Keep the license notice with your copy.
Example version 1.0.0 · Documentation reviewed 2026-11-16.
24 recorded CLI cases passed in rootless Docker on the pinned Python 3.12 runtime, with 512 MiB RAM, 1 CPU, no network, and read-only source. Other runtimes and all possible inputs are not verified.