PeaBox Lab › PeaLang › Learn › Chapter 8 › Lesson 3

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:

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.

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.

CheckExampleStable reason code
Required fieldidentifier is presentMISSING_FIELD
Typequantity is a numberINVALID_TYPE
Rangequantity is not negativeOUT_OF_RANGE
Allowed valuesstatus is a known codeINVALID_VALUE
Unknown fieldpolicy rejects or ignores extrasUNKNOWN_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

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 whenUse 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

ConceptPurposeDesign note
Literal charactersMatch exact text.Escape special characters from user input.
Character classesMatch one character from a set.State whether Unicode letters are intended.
QuantifiersRepeat an element.Prefer explicit upper bounds.
AnchorsFix start or end position.Use full-string validation intentionally.
Groups and capturesExtract and organize fragments.Name captures when the engine supports it.
AlternationChoose 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.

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

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.

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

MistakeCorrection
Treating successful parsing as validationValidate fields, types, ranges, and unknown keys.
Splitting CSV text on commasUse the standard CSV facility with an explicit dialect.
Depending on column positionValidate headers and map by name.
Parsing JSON with a regular expressionUse the JSON parser and validate the result.
Using an unanchored validation patternRequire a full-string match.
Accepting ambiguous nested quantifiersUse narrow classes, bounds, and deadlines.
Logging rejected raw inputLog row numbers, codes, and redacted summaries.
Using floating-point for exact moneyUse the approved exact or scaled representation.
Ignoring formula-trigger text in exported cellsApply a documented neutralization policy.

3.20 Diagnostic workflow

3.21 Guided practice

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

Required tests

Deliverables

Acceptance criteria

3.23 Review questions

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.

← Previous Next →