Part III — Advanced Systems · Chapter 16 · Lesson 2 of 6 · 17 min read
Lesson 2: Schema Inference and CSV, JSON, and JSONL Interchange
Lesson level: Advanced
Purpose: Read and write tabular data in the three most common interchange formats without losing types, precision, or time-zone information. Learn how schema inference decides on types, how to control it, and how to turn an inferred schema into a declared one that protects production pipelines.
Release note: reader and writer options in this lesson follow the illustrative std.data API for PeaLang v0.63 RC2. Verify option names against the data reference before relying on them.
Learning objectives
By the end of this lesson you will be able to:
- explain how inference samples rows and resolves conflicting types;
- control inference with sample size, type overrides, null markers, and date formats;
- read and write CSV with explicit delimiters, quoting, encodings, and headers;
- read and write JSON arrays and JSONL streams, including nested structures;
- preserve Decimal and Timestamp values exactly across a write and read round trip;
- promote an inferred schema to a declared, versioned schema.
2.1 What inference does, and what it cannot do
Schema inference looks at sample values in each column and picks the narrowest DataType that fits all of them. It is useful for exploring unfamiliar files and for drafting a schema quickly. It is not a substitute for a declared schema, because inference can only describe the data it saw, not the data the business intends.
Inference walks each column through a fixed ladder of candidate types and moves up one rung whenever a value does not fit:
Null -> Bool -> Int64 -> Decimal -> Float64 -> Utf8
\
-> Date -> Timestamp -> Utf8
A column of 1, 2, 3 becomes Int64. Add 4.50 and it becomes Decimal with the largest scale seen. Add 1e3 and it becomes Float64, because exponents are not exact decimals. Add n/a and it becomes Utf8, unless n/a is declared as a null marker. Date and Timestamp are tried only when every non-null value matches one of the accepted formats.
| Sample values | Inferred type | Why |
|---|---|---|
| "1", "2", "", "4" | Int64 (nullable) | Empty string is the default null marker |
| "19.99", "5", "0.5" | Decimal(p, 2) | Largest scale seen is 2; no exponents |
| "19.99", "2.5e2" | Float64 | Exponent forces binary floating point |
| "2026-10-31", "2026-11-01" | Date | All values match ISO date |
| "2026-10-31T07:54:00Z", "2026-10-31T09:00:00+05:30" | Timestamp(ms, UTC) | Offsets are normalized to UTC |
| "2026-10-31 07:54:00" | Timestamp(ms, null) | No zone: naive timestamp, flagged with a warning |
| "true", "false", "yes" | Utf8 | "yes" is not a boolean unless configured |
| "007", "042" | Int64 — dangerous | Leading zeros are lost; declare as Utf8 |
The last row is the classic inference failure. Postcodes, product codes, account numbers, and phone numbers look like integers but are identifiers. Inference cannot know that; your schema must say so.
2.2 Controlling inference
Inference has five controls. Use them while exploring, then capture the result as a declared schema.
import std.data as d
let schema = d.infer_csv_schema("data/customers.csv",
sample_rows: 10_000, // default 1,000; use -1 to scan the whole file
null_values: ["", "NULL", "n/a", "-"],
overrides: {
"postcode": d.Utf8, // identifiers stay text
"account_no": d.Utf8,
"credit_limit": d.Decimal(18, 2), // never let money become Float64
},
date_formats: ["%Y-%m-%d", "%d/%m/%Y"],
timestamp_formats: ["%Y-%m-%dT%H:%M:%S%.3f%:z", "%Y-%m-%d %H:%M:%S"],
assume_timezone: "UTC", // applied to naive timestamps
)
print schema
print schema.inference_report()
The inference report records, for each column, the rows sampled, the nulls seen, every type the column passed through on the ladder, and the first value that forced each promotion. That last item is the most useful: it tells you exactly which row turned your integer column into text.
// inference_report() excerpt
// column type nulls promotions
// customer_id Utf8 0 -
// postcode Utf8 (override) 12 -
// signup_date Date 3 Null->Date
// credit_limit Decimal(18,2) 0 Int64->Decimal at row 41 ("2500.50")
// segment Utf8 0 Bool->Utf8 at row 2 ("gold")
// last_seen Timestamp(ms,UTC) 88 naive values localized with assume_timezone
Sample size matters. A sample of 1,000 rows will happily infer Int64 for a column whose first text value appears at row 50,000. The read then fails late, or worse, silently nulls the value if the reader is lenient. For exploration, scan the whole file once with sample_rows: -1; for production, do not infer at all.
Date ambiguity. 03/04/2026 is 3 April in most of the world and 4 March in the United States. Inference refuses to guess: if both %d/%m/%Y and %m/%d/%Y are listed and every value fits both, the column stays Utf8 and the report flags it as ambiguous. Give one format per source system.
2.3 From inferred to declared
An inferred schema is a draft. Promote it to a declared schema in a module, review it like code, and version it. The to_source method writes the PeaLang declaration for you.
print schema.to_source(name: "CUSTOMER_SCHEMA_V1")
// Output — paste into schemas/customers.pea and edit:
const CUSTOMER_SCHEMA_V1 = d.Schema([
d.Field("customer_id", d.Utf8),
d.Field("name", d.Utf8),
d.Field("postcode", d.Utf8, nullable: true),
d.Field("signup_date", d.Date, nullable: true),
d.Field("credit_limit", d.Decimal(18, 2)),
d.Field("segment", d.Utf8),
d.Field("last_seen", d.Timestamp("ms", "UTC"), nullable: true),
])
While editing, ask four questions of each field. Is the type the business type, not just the observed one (for example, should segment be Categorical)? Is nullability what the business allows, not just what the sample happened to contain? Is the precision of each Decimal enough for the largest legitimate value? And is every timestamp zone-aware?
Then read with the declared schema and strict mode. Strict mode fails on the first row that does not match, with the row number and the offending value.
import schemas.customers.{CUSTOMER_SCHEMA_V1}
let customers = d.read_csv("data/customers.csv",
schema: CUSTOMER_SCHEMA_V1,
strict: true,
null_values: ["", "NULL"])
2.4 Reading CSV
CSV looks simple and is not. There is no single standard for delimiters, quoting, line endings, encodings, or headers, and every spreadsheet tool has its own habits. Make each choice explicit so the reader does not guess.
let orders = d.read_csv("data/orders.csv",
schema: ORDER_SCHEMA_V1,
header: true, // first row holds column names
delimiter: ",", // ";" is common in European exports
quote: "\"",
escape: "\"", // doubled quotes inside quoted fields
encoding: "utf-8", // or "utf-8-sig" to strip a byte-order mark
null_values: ["", "NULL"],
trim_whitespace: true,
skip_rows: 0,
columns: null, // or a list to read a subset
strict: true)
Four options cause most production problems:
| Option | Typical failure | Guidance |
|---|---|---|
| delimiter | A semicolon-separated export read as one wide column | Fix per source system; never sniff in production |
| encoding | "Müller" instead of "Müller"; a stray \ufeff in the first header | Require UTF-8; use utf-8-sig for spreadsheet exports |
| header | First data row silently becomes column names | Declare header explicitly and validate names against the schema |
| null_values | The string "NA" (Namibia) read as null | List only markers the source really uses |
Header matching. With a declared schema, the reader matches columns by name, not by position. Extra columns in the file raise an error unless extra_columns: "ignore" is set; missing required columns always raise an error. Matching by name protects you when a source system reorders its export.
Bad rows. Strict mode stops at the first bad row. For ingestion pipelines that must continue, use on_error: "quarantine", which returns the good rows and a second DataFrame of rejected rows with their line number and reason. Chapter 17 builds on this pattern.
let result = d.read_csv("data/orders.csv", schema: ORDER_SCHEMA_V1,
on_error: "quarantine", max_errors: 500)
let good = result.data
let rejected = result.rejected // columns: line, raw, field, reason
print str.format("{} good, {} rejected", good.height, rejected.height)
Set max_errors. A file in which most rows are bad is usually the wrong file or the wrong delimiter, and the read should fail rather than quarantine everything.
2.5 Reading JSON and JSONL
JSON carries types that CSV cannot: numbers, booleans, nulls, nested objects, and arrays. Two layouts are common. A JSON array holds every record inside one top-level list. JSONL (JSON Lines) holds one complete JSON object per line.
// orders.json — one array
[
{"order_id": 1, "customer": {"id": "C000123", "tier": "gold"}, "amount": "120.50",
"tags": ["web", "promo"], "ordered_at": "2026-10-31T07:54:00.000Z"},
{"order_id": 2, "customer": {"id": "C000456", "tier": "standard"}, "amount": "80.00",
"tags": [], "ordered_at": "2026-10-31T08:10:12.500Z"}
]
// orders.jsonl — one object per line
{"order_id": 1, "customer": {"id": "C000123", "tier": "gold"}, "amount": "120.50", ...}
{"order_id": 2, "customer": {"id": "C000456", "tier": "standard"}, "amount": "80.00", ...}
2.6 Nested records: choose a table grain
Continuation note. This lesson continues the JSON and JSONL discussion. The earlier module paths, extended types, reader options, and method spellings are illustrative. The examples below describe transformation contracts rather than promise executable v0.63 APIs. Replace conceptual operations with verified calls before running a lab.
JSON can represent a customer object and a list of tags inside one order. A table must make an additional decision: what does one row represent? This is the grain. If the grain is one order, extracting customer.id and customer.tier into columns preserves that grain. Expanding tags creates one row per order–tag pair and changes it.
Write the grain before choosing a transformation. For an order table, order_id identifies the order, customer_id links to a separate customer table, and tags may remain a list or move into a child table. Do not expand a list merely because flattening is convenient. Repeated order amounts can later be summed more than once.
Illustrative transformation contract: read each complete order object; retain order_id; extract customer.id as customer_id and customer.tier as customer_tier; preserve the amount text until its numeric representation is validated; retain tags separately. Reject records whose required customer object is absent or has the wrong shape.
Missing, null, and empty are different. A missing tags field may mean an incomplete export. A null field may mean unknown. An empty list may mean the order has no tags. The contract must decide whether these cases are equivalent; the reader cannot infer that business meaning.
Guided practice
Describe two outputs for the sample orders: an order table and an order_tags table. State each table’s grain, key, and relationship. Explain how an order with no tags remains visible in the order table.
Common mistake: flattening two independent lists in one step can multiply combinations. Expand each relationship separately unless every combination is genuinely required.
Check your understanding: Why must an order amount not become an additive measure in an order–tag table without an explicit allocation rule?
2.7 Normalization: preserve meaning before converting types
Normalization makes a source representation fit a declared contract. It is not permission to repair every surprising value silently. Begin with the source specification, identify allowed representations, and record each intentional conversion. Preserve the raw value when a rejected record must be investigated.
For customer identifiers, whitespace trimming may be allowed while removal of leading zeros is not. For region labels, a documented mapping might translate North and NORTH into north. For amounts, a decimal separator must be known rather than guessed. For timestamps, an offset and a local clock reading cannot be treated as interchangeable.
Illustrative normalization sequence: validate the record shape; map documented field names; trim only approved text fields; apply a controlled category mapping; parse numbers using the agreed representation; interpret timestamps using a declared time-zone rule; check required fields and ranges; emit a normalized row or a rejection record.
Keep representation validation separate from business validation. A value can parse as a number yet violate the permitted range. A timestamp can be syntactically valid yet belong to an impossible reporting period. A customer identifier can be nonempty yet fail a lookup against the customer reference table.
Do not label a converted timestamp as UTC unless the conversion establishes the instant. A source clock reading without an offset requires a source time-zone policy; changing its label alone does not convert it. Around daylight-saving transitions, some local readings can be ambiguous or nonexistent.
Guided practice
Prepare a normalization register with columns for source field, accepted representation, transformation, output representation, and rejection reason. Include customer_id, region, amount, and ordered_at. Use hypothetical values and mark them as such.
Common mistake: a catch-all conversion of every value to text can hide an invalid numeric or boolean field. It postpones the defect until a later computation.
Applied question: If a source changes from decimal points to decimal commas, should the pipeline adapt automatically or require a contract change? Explain how the choice protects reproducibility.
2.8 Schema inference is discovery, not approval
Inference observes available records and proposes a schema. Its result depends on the inspected data. A small sample may contain only integers even though later rows contain fractional values. An optional field may be absent throughout the sample. A column containing only nulls provides little evidence about its intended type.
Use inference to learn about an unfamiliar export, then compare the proposal with a deliberate target schema. Record the sampling scope, observed categories, null patterns, and conflicting representations. Do not convert the proposal directly into a stable production contract without review.
The distinction between observation and guarantee matters. Seeing only valid dates does not establish a permanent date format. Seeing unique order identifiers does not prove that future files cannot repeat them. Seeing no nulls does not prove that the source guarantees completeness.
Illustrative discovery report: candidate field names; observed value categories; fields missing from some records; all-null fields; representation conflicts; proposed conversions; unresolved decisions. This is a design artifact, not an assertion about a built-in reporting method.
Once approved, a target schema should remain stable for a defined version. Incoming data is checked against that version. New optional columns may be accepted under an explicit policy; missing required columns or incompatible changes require rejection or a versioned migration.
Guided practice
Imagine that the sample contains amount values written as whole numbers, but a later row contains a decimal string. List the questions you must answer before choosing the output representation. Include whether precision is contractual and whether text-to-number conversion is permitted.
Common mistake: using one convenient sample to claim support for the entire source. Include boundary records, optional fields, missing values, and conflicting representations in discovery.
Review prompt: Explain the difference between a column observed to contain no nulls and a field contractually required to contain no nulls. What evidence would support the stronger claim?
2.9 Nulls, malformed records, and rejection policy
Missing data must remain distinguishable from valid data. A missing order amount is not automatically zero. A missing customer tier is not automatically standard. Substitution may make the pipeline run while changing the meaning of its output.
Define separate handling for absent fields, explicit nulls, empty strings, invalid representations, and out-of-range values. Where the domain treats two cases alike, document the equivalence. Otherwise retain separate reason codes so the quality report explains what occurred.
A rejection policy has two levels. At the record level, decide whether one malformed row can be isolated while valid rows continue. At the file level, decide whether the source is trustworthy enough to process at all. A wrong delimiter, unrecognized schema version, or missing required header may invalidate the whole file.
Illustrative rejection record: source identifier, logical record position, field name, reason code, safe excerpt, and schema version. Store full raw records only in an appropriately controlled location. Diagnostic convenience does not justify unrestricted retention of personal or confidential data.
For JSONL, a physical line can identify a record only when the file obeys the one-object-per-line convention. For CSV, quoted fields can contain line breaks, so physical line count and logical record count need not coincide. Explain which location convention your report uses.
Annotated decision example
An order with a valid identifier and an amount containing unrecognized text should be rejected with an amount-representation reason, not accepted with a zero amount. A file lacking the order_id header should fail its file-level contract before row processing begins.
Guided practice: classify an absent customer object, a null optional note, an empty order identifier, an unknown region, and an invalid amount. For each, state whether processing continues and what evidence is retained.
Common mistake: reporting only rejected-row totals. Add reason categories and affected source versions; otherwise a recurring contract failure can hide behind a stable headline count.
2.10 Interchange and round-trip guarantees
A round trip writes a table to an interchange format and reads it back. Success means preservation of the properties promised by the contract, not merely that both operations complete. Define what must survive: field names, identifiers, values, nulls, units, ordering where meaningful, and schema metadata where supported.
CSV represents cells as text. The target schema must restore intended value types. JSON distinguishes several basic value categories, but an exact decimal, a wide integer, or a timestamp may still require an agreed string representation. Do not assume that a different host reconstructs those values exactly without an explicit rule.
Choose a fidelity policy for each field. An identifier is usually compared exactly. A category may be compared after an approved normalization. A measurement may use a justified numeric tolerance. A currency amount needs an agreed exact representation or a documented rounding policy. Missing values need their own equivalence rule.
Illustrative round-trip procedure: prepare a small adversarial fixture; write it; read it under the target schema; compare keys and values; compare null patterns; inspect rejected records; explain every difference. Keep the writer configuration with the evidence.
Include text containing commas, quotes, line breaks, and non-ASCII characters. Include an identifier with leading zeros, a zero measurement, a null optional field, and a timestamp with an offset. Ordinary rows alone do not test the fragile parts of interchange.
Guided practice
Write a fidelity contract for customer_id, ordered_at, amount, note, and tags. State whether each must compare exactly, compare after normalization, or use a tolerance. Explain which metadata may need a companion schema rather than the data file itself.
Common mistake: comparing only printed table summaries. A display may truncate text, abbreviate rows, or format numbers. Compare contractual values rather than screenshots or presentation text.
Review prompt: What would make a CSV round trip acceptable even if the file bytes differ? Conversely, what value change would make it unacceptable despite identical row counts?
Common mistakes
- Trusting inference in production: inferred schemas describe a sample, not a contract. Promote them to declared schemas before scheduled runs.
- Inferring from too few rows: late-appearing values such as decimals or nulls are missed. Scan a representative sample or declare the type.
- Mixing JSON and JSONL: a JSON array and newline-delimited records need different readers; choose by file contract, not extension alone.
- Silently coercing bad values to null: record rejected rows with reasons so data loss is visible.
- Flattening nested data without naming rules: agree a stable column-naming convention before downstream joins depend on it.
- Ignoring encoding and delimiter settings: state them explicitly for CSV inputs that come from other systems.
2.11 Hands-on lab: A controlled interchange boundary
Scenario. A hypothetical order export arrives in CSV, JSON-array, and JSONL forms. Build a common normalized order table without claiming that every reader option shown earlier exists in the installed runtime. First map each required operation to a verified API or a host-side adapter.
Objectives. Demonstrate schema approval, representation validation, safe rejection, and round-trip comparison. Preserve one-order-per-row grain and keep nested tag relationships separate.
- Define required order_id, customer_id, amount, and ordered_at fields, plus optional region, note, and tags. State accepted representations and null policy.
- Create equivalent synthetic fixtures in all three formats. Include leading-zero identifiers, quoted text, non-ASCII names, optional nulls, and a nested customer object.
- Create separate defective fixtures: missing required field, malformed amount, unknown category, incomplete JSONL record, and unexpected schema version.
- Document reader settings actually supported by the installed environment. Identify where a host adapter is needed.
- Normalize valid records into the same target representation. Emit controlled rejections and stop on file-level contract failures.
- Write the normalized result and perform the fidelity checks from section 2.10.
Use an evidence table with these columns: fixture, source format, expected result, observed result, rejection reason, and correction. Leave observed results blank until the test runs; anticipated outcomes are not execution evidence.
Acceptance criteria. Valid fixtures produce equivalent contractual records. Invalid values are not replaced silently. Required-field failures are visible. Rejections disclose no secrets. The report identifies schema and reader configuration versions. Round-trip differences are either absent or explained by an approved policy.
Common mistakes. Mixing malformed-record tests into the valid fixture makes comparison harder. Losing the raw identifier during numeric conversion prevents later recovery. Treating a parsing failure as a business-rule failure misdirects the correction.
Deliverable. Submit fixtures, target contract, verified API mapping, normalization design, rejection report, and observed round-trip results. Include a short note separating runtime capabilities from adapter responsibilities.
2.12 Review, applied challenge, and lesson summary
Interchange is a boundary between representations and meanings. The same records can appear as CSV cells, a JSON array, or JSONL objects, but the target contract must establish grain, keys, types, nulls, and acceptable conversions. A reader completing successfully is necessary, not sufficient.
Review questions
- How does expanding tags change an order table’s grain?
- Why are missing, null, and empty values not automatically equivalent?
- When should a malformed row invalidate an entire file?
- What information does an inference sample fail to guarantee?
- Why must leading-zero identifiers remain text unless the contract says otherwise?
- What extra policy is needed for a timestamp without an offset?
- Which properties should a round-trip test compare?
- Why are physical lines and logical CSV records different concepts?
Suggested reasoning. Grain describes the entity represented by one row. Null policy describes meaning rather than convenience. Inference reports observations. Rejections explain violations. Fidelity tests protect contractual values across serialization. These ideas apply even when the concrete reader implementation changes.
Applied challenge
Design an ingestion contract for a supplier whose export sometimes adds optional columns. Preserve existing required fields, accept only documented additions, and produce a schema-change report. Explain when a new version is required and how old fixtures remain part of regression testing.
Then imagine that the supplier changes a customer identifier into a number and removes leading zeros. Decide whether this is safely reversible. Identify the evidence needed to reconstruct the original identifiers and explain why guessing is unacceptable.
Lesson summary. Discover source structure, approve a target schema, normalize only documented representations, preserve grain, reject visibly, and test fidelity. Keep illustrative API spellings separate from verified runtime behavior.
Lesson status: Ready for review.