Part II — Intermediate Development · Chapter 8 · Lesson 3 of 6 · 11 min read
Lesson 3: JSON, CSV, and Regular Expressions
Lesson level: Intermediate
Purpose. Parse, validate, transform, and emit structured and pattern-based text safely, using the right tool for each format and keeping untrusted input bounded.
Learning objectives
By the end of this lesson, you will be able to:
- Parse and serialize JSON while preserving PeaLang’s portable-value boundary.
- Validate decoded documents against an explicit schema contract.
- Read and write CSV with correct quoting, headers, types, and error handling.
- Choose regular expressions only for pattern problems they solve well.
- Prevent pathological matching, oversized input, and ambiguous patterns.
- Report parse and validation failures with stable, safe diagnostics.
- Test malformed, boundary, Unicode, and adversarial inputs.
3.1 Parse, validate, then trust
Structured text is external input. Decoding it successfully proves only that the syntax was acceptable; it does not prove that required fields exist, values have the right types, numbers are in range, or the document is safe to process. Treat every structured-text workflow as three stages: parse, validate, and only then use.
Release note. The function names in the examples are illustrative. Confirm exact modules, options, and failure behavior with the standard-library manifest and documentation for the installed release.
3.2 JSON and the portable-value model
JSON maps naturally onto PeaLang’s portable values: null, booleans, numbers, strings, lists, and string-keyed maps. That fit makes JSON a good interchange format for host boundaries, configuration, and service responses.
- Object keys are strings; maps used for JSON should use string keys.
- Decoded numbers may be integers or floating-point values; verify which representation your logic requires.
- Values outside the portable model, such as host objects, functions, and cyclic structures, are not valid serialization input.
- Duplicate object keys, extremely deep nesting, and very large numbers are boundary conditions that the parser contract must define.
3.3 Decoding safely
A decoding adapter should enforce limits before and during parsing: maximum input size, maximum nesting depth, maximum collection size, and an overall deadline. Convert parser failures into a stable application error category rather than leaking raw parser internals or the full rejected document.
function decode_request(text): if size_of(text) > max_request_bytes { return failure("REQUEST_TOO_LARGE") } document = std.json.parse(text) // illustrative return validate_request(document)
Do not evaluate decoded content as code, use it to build file paths without validation, or pass it directly to privileged operations.
3.4 Validating a decoded document
A validation contract states, for every field, whether it is required, its allowed type, range or length, permitted values, and treatment of unknown fields. Validation should collect or report all material problems consistently and return a normalized portable value that the core logic can trust.
| Check | Example | Stable reason code |
|---|---|---|
| Required field | identifier is present | MISSING_FIELD |
| Type | quantity is a number | INVALID_TYPE |
| Range | quantity is not negative | OUT_OF_RANGE |
| Allowed values | status is a known code | INVALID_VALUE |
| Unknown field | policy rejects or ignores extras | UNKNOWN_FIELD |
Distinguish a missing key from a key whose value is null. Decide whether null means absent, unknown, or invalid for each field, and document the answer.
3.5 Encoding JSON deliberately
Serialization should produce output that downstream consumers can rely on. Build a canonical portable value first, validate it against the outgoing contract, and then encode it. When output is compared, signed, hashed, or used as a cache key, rely on an explicitly documented canonical form including key order, number representation, and whitespace policy.
Do not serialize secrets, credentials, or unnecessary personal data. Redact before encoding so sensitive values cannot appear in later logs or error messages.
3.6 Numeric precision in interchange
Large integers, decimal currency amounts, and floating-point values can lose or change meaning across systems. Decide how identifiers, money, and measurements are represented. A common safe choice is to transmit identifiers and exact decimal quantities as strings or scaled integers while documenting the conversion rules.
3.7 CSV is a format with rules
CSV looks simple but contains quoted fields, embedded delimiters, embedded line breaks, escaped quotes, optional headers, blank fields, encoding differences, and variant dialects. Splitting a line on commas is not a CSV parser.
A CSV contract specifies encoding, delimiter, quote character, line-break policy, header presence, required columns, column order sensitivity, null or empty-value meaning, and maximum row, field, and file sizes.
3.8 Reading CSV safely
- Bound the input size and row count.
- Parse with the standard CSV facility and an explicit dialect.
- Validate the header: required columns exist, names are unique, and unexpected columns follow policy.
- Map each row into a validated record using column names, not fragile positions.
- Convert text to numbers, dates, and booleans using explicit parsers.
- Track row numbers for diagnostics without logging sensitive cell contents.
- Choose a failure policy: reject the whole file, reject invalid rows, or quarantine them for review.
3.9 Writing CSV safely
Use the standard writer so fields containing delimiters, quotes, or line breaks are quoted correctly. If a spreadsheet application may open the output, treat fields beginning with formula-trigger characters as a security concern and apply a documented neutralization policy for user-controlled text. Never assume the consumer will interpret cells only as plain text.
3.10 JSON or CSV?
| Use JSON when | Use CSV when |
|---|---|
| Data is nested or heterogeneous. | Data is flat and tabular. |
| Types and null values matter. | Spreadsheet or batch exchange is the main workflow. |
| A schema can validate fields precisely. | Row-by-row streaming and compact files are important. |
3.11 When regular expressions fit
Regular expressions describe patterns in text. They are well suited to bounded token formats, simple validation of identifiers, extraction of labeled fragments, and controlled search-and-replace. They are poor tools for parsing nested structures, complete JSON or CSV documents, HTML, or any grammar that needs recursion or context.
Prefer the dedicated parser when one exists. Use a pattern only after the structured parser has isolated the field you intend to match.
3.12 Pattern building blocks
| Concept | Purpose | Design note |
|---|---|---|
| Literal characters | Match exact text. | Escape special characters from user input. |
| Character classes | Match one character from a set. | State whether Unicode letters are intended. |
| Quantifiers | Repeat an element. | Prefer explicit upper bounds. |
| Anchors | Fix start or end position. | Use full-string validation intentionally. |
| Groups and captures | Extract and organize fragments. | Name captures when the engine supports it. |
| Alternation | Choose among alternatives. | Keep alternatives distinct and ordered deliberately. |
Always confirm the supported syntax, flags, Unicode behavior, and capture-reporting model in the installed release rather than assuming another language’s dialect.
3.13 Anchoring and validation
An unanchored pattern may match a substring and accept invalid input. For validation, require the entire value to match. For search or extraction, define the surrounding boundaries so a nearby but unrelated fragment cannot satisfy the pattern.
Illustrative design: a case identifier consisting of the prefix CASE, a hyphen, and four to eight digits should be validated as the complete string, not found anywhere inside a larger sentence.
3.14 Greedy, lazy, and ambiguous matching
Greedy quantifiers consume as much text as possible, while lazy forms prefer less. Ambiguous nested quantifiers can force an engine to explore a large number of ways to match the same text. Treat patterns from untrusted users as dangerous unless the engine contract guarantees bounded behavior.
- Avoid nested repetition of overlapping subpatterns.
- Replace broad wildcards with narrow character classes.
- Bound input length before matching.
- Apply runtime deadlines and instruction or time limits.
- Test long near-miss inputs designed to fail late.
3.15 Captures, replacement, and splitting
Captured text is still untrusted text. Validate extracted fragments before converting them to numbers, dates, paths, or commands. When replacing text, confirm whether the operation changes the first match or all matches, how backreferences work, and how special characters in replacement strings are interpreted.
Do not build a pattern by concatenating user input unless that input is escaped as a literal. Better still, let users choose from approved options rather than supply pattern syntax.
3.16 Unicode and normalization
Visible characters, case behavior, combining marks, and digit sets vary across languages and encodings. Decide whether the system accepts only ASCII identifiers or broader Unicode text. If equivalence matters, normalize first using the documented text facility, then match the canonical form.
3.17 Choosing the safest tool
- Use JSON and CSV parsers for structured documents.
- Use exact comparison or fixed-prefix functions for fixed text.
- Use a regular expression for a narrow, bounded pattern.
- Use a dedicated parser or grammar for nested or context-sensitive syntax.
3.18 Integrated example: validated import report
An import utility receives a JSON control document and a CSV file of synthetic transaction rows. It must produce a deterministic report.
- Check capability and size limits for both inputs.
- Decode and validate the JSON control document, including the expected column names and a bounded maximum row count.
- Parse the CSV with an explicit dialect and validate its header against the control document.
- Convert each row into a typed record using explicit numeric and date parsers.
- Use a narrowly anchored, bounded pattern only for the transaction-code field.
- Collect stable row-level rejection codes without logging sensitive cell contents.
- Sort results explicitly and emit a canonical JSON report.
Invariants. Accepted rows plus rejected rows equal parsed rows; every rejection has a row number and reason code; no output contains secrets; repeated runs with the same inputs produce identical output.
3.19 Common mistakes and corrections
| Mistake | Correction |
|---|---|
| Treating successful parsing as validation | Validate fields, types, ranges, and unknown keys. |
| Splitting CSV text on commas | Use the standard CSV facility with an explicit dialect. |
| Depending on column position | Validate headers and map by name. |
| Parsing JSON with a regular expression | Use the JSON parser and validate the result. |
| Using an unanchored validation pattern | Require a full-string match. |
| Accepting ambiguous nested quantifiers | Use narrow classes, bounds, and deadlines. |
| Logging rejected raw input | Log row numbers, codes, and redacted summaries. |
| Using floating-point for exact money | Use the approved exact or scaled representation. |
| Ignoring formula-trigger text in exported cells | Apply a documented neutralization policy. |
3.20 Diagnostic workflow
- Identify the failing layer: size limit, syntax parse, schema validation, conversion, pattern match, or output encoding.
- Reproduce with the smallest synthetic input that still fails.
- Check encoding, delimiter, quote, header, null, and Unicode assumptions.
- Confirm the exact documented behavior of the installed standard-library function.
- Inspect the first failing field or row rather than the final symptom.
- Add a regression test for the failing input class.
3.21 Guided practice
- Write a validation contract for a request containing identifier, quantity, status, and optional notes.
- Decide how null, missing, and empty-string notes should be treated.
- Describe a canonical JSON output policy for a signed report.
- Create a CSV header contract with required, optional, and forbidden columns.
- Explain why a quoted field containing a line break breaks naive line splitting.
- Design a bounded pattern for a synthetic identifier and list three accepted and three rejected examples.
- Explain why a nested quantifier pattern is risky on untrusted input.
- Choose JSON, CSV, a pattern, or a dedicated parser for four listed data-processing tasks.
3.22 Hands-on lab: Build a safe import validator
Scenario. Build a PeaLang utility that reads a synthetic JSON control document and a synthetic CSV transaction file, validates both, and emits a deterministic JSON validation report. Use no real personal or financial data.
Control-document contract
The JSON control document contains a schema version, expected column names, a maximum row count, an allowed status list, and the transaction-code pattern name. Unknown critical fields are rejected.
CSV contract
The file is UTF-8 text with a header row and columns for transaction code, amount, status, and note. Quoted fields, embedded commas, escaped quotes, and embedded line breaks are valid.
Required behavior
- Reject oversized control or CSV input before parsing.
- Decode the control document and validate every field and type.
- Parse the CSV with an explicit dialect and validate the header.
- Convert amounts using the approved exact or scaled representation.
- Validate transaction codes with a bounded, fully anchored pattern.
- Reject unknown statuses and negative amounts with stable reason codes.
- Preserve row numbers and omit raw cell values from diagnostics.
- Return accepted count, rejected count, per-reason counts, and ordered rejection records.
- Emit canonical JSON with an explicit key order.
Required tests
- valid control document and valid file;
- malformed JSON and wrong JSON types;
- missing, duplicate, and unexpected columns;
- quoted commas, escaped quotes, and embedded line breaks;
- empty file and header-only file;
- maximum row count and one row above it;
- valid and invalid transaction codes at pattern boundaries;
- a long near-miss input intended to stress the pattern;
- Unicode text in the note field;
- a formula-like note neutralized in any CSV output;
- repeated runs producing identical output.
Deliverables
- the validator source and synthetic test files;
- the JSON and CSV boundary contracts;
- a table of reason codes and their meanings;
- expected and actual results for every required test;
- a compatibility note listing the standard-library modules and capabilities used.
Acceptance criteria
- No decoded or parsed value reaches core logic before validation.
- Accepted plus rejected rows equal parsed rows.
- Every rejection has a row number and stable reason code.
- No rejection record contains raw sensitive cell content.
- The pattern is bounded, anchored, and tested against pathological input.
- Output is canonical and deterministic.
- Formatting, semantic checks, and tests pass as separate gates.
3.23 Review questions
- Why does successful JSON parsing not prove that a document is valid for the application?
- How should a missing key differ from an explicit null?
- Which resource limits should be applied before decoding untrusted text?
- Why can numeric values change meaning during interchange?
- Why is splitting a CSV line on commas incorrect?
- What should a CSV header contract specify?
- When is rejecting a whole file better than rejecting individual rows?
- Why is an unanchored validation pattern dangerous?
- What makes nested quantifiers risky?
- Why should captured text still be validated?
- Which parser is appropriate for nested structured data?
- How can diagnostics remain useful without exposing sensitive content?
3.24 Applied challenge
Extend the validator to process a JSON Lines-style stream of synthetic records while enforcing a global byte limit, a per-record size limit, and a maximum record count. Return a deterministic summary that distinguishes syntax errors, schema errors, conversion errors, and limit violations. Add tests for partial final records, blank lines, repeated keys, extremely deep nesting, and mixed valid and invalid records.
Lesson summary
Reliable structured-text processing follows the sequence of bounded parsing, explicit validation, and controlled use. JSON fits PeaLang’s portable-value model but still needs schema, numeric, and size policies. CSV requires a real parser, an explicit dialect, header validation, typed conversion, and safe output. Regular expressions are best reserved for narrow, anchored, bounded patterns; dedicated parsers should handle structured documents. Stable diagnostics, redaction, determinism, and adversarial tests make these operations dependable.
Transition to Lesson 4
The next lesson moves from in-memory text and data to controlled interaction with the environment: files, paths, HTTP, cryptography, logging, testing, and concurrency.
Lesson status: Ready for review.