AAmit’s LibraryLEARN · PRACTISE · REFLECT

Computers · Programming Atlas

Data Formats Foundations

JSON, CSV/TSV, XML and TOML reading, serialization where supported, explicit encoding, escaping, dialects, syntax errors and small hand-written contracts. No schema engine, external files or untrusted XML parsing.

Audience: Learners comfortable with the Python Foundations examples.

Practice: 4 to 6 hours.

Runtime and boundaries: Run each .py with the installed Python interpreter. Tests use CPython 3.9.6, which is unsupported upstream. JSON, CSV and XML use the standard library. TOML uses the already installed pip._vendor.tomli 1.0.3 fallback; this private API may change or disappear and is not a stable public pip interface. The preferred tomllib branch requires an already installed Python 3.11+ and is not tested here. No dependency is installed. XML examples are limited to tiny trusted authored strings; do not reuse their entry points for untrusted XML.

Lessons

Formats are not programming languages

JSON and CSV/TSV are data formats, TOML is a configuration format, and XML is a markup language. Parsers turn text into values or trees; they do not automatically enforce an application schema. JSON Schema and XML Schema remain planned registry entries.

Encoding and resource bounds

Agree on UTF-8 at file boundaries and use strict decoding; do not silently replace invalid bytes. Keep examples tiny and in memory. Apply byte, row and value limits before expensive processing where possible. Limits in these toys do not make an arbitrary deeply nested or malicious document safe.

JSON syntax and policy

JSON values include objects, arrays, strings, numbers, booleans and null. Use serializers for escaping; do not build JSON by string concatenation. Python defaults accept NaN and repeated object names, so a stricter contract can reject both with hooks. Reject nonfinite values before encoding; huge JSON numeric exponents also need finite-value checks after decoding.

CSV and TSV dialects

A delimiter alone is not a complete dialect. Specify quoting, escaping, line endings, headers and encoding. Do not split lines on commas or tabs when quoted fields may contain those characters. Parse first, then check row width and convert selected cells. Do not infer a schema just because a numeric-looking cell parses.

Safe export boundaries

CSV writers quote delimiters and line breaks; this prevents structural corruption, not spreadsheet formula execution. Values beginning with formula-like characters require a destination-specific reviewed export policy before spreadsheet use. No spreadsheet is opened by the examples. JSON, XML and CSV need their own serializers; escaping is context-specific.

XML trees and trust

XML well-formedness, namespaces and application structure are different checks. Build elements and assign text instead of splicing markup. ElementTree is not hardened for malicious XML; this pack only parses tiny authored strings and never accepts untrusted XML files, DTDs or entity definitions. Installing a hardened parser is outside this task.

TOML configuration

TOML 1.0 has tables, arrays, strings, booleans, numbers and date/time values. Keys cannot be defined twice. A parser returns typed values; it does not enforce required application settings. Date/time values may need explicit conversion when moving into JSON. The examples use a small subset and do not test TOML 1.1 or writing TOML.

Error handling and schema boundaries

Catch the relevant parser error and validate the resulting values separately. Our hand-written contracts are narrow educational checks, not a JSON Schema or XSD engine. Python 3.9.6 and its private pip-vendored Tomli fallback are installed test constraints, not deployment recommendations. Use only authored local examples; all other runtimes remain untested.

Reference cards

Encoding: text.encode("utf-8")

Converts text to bytes; record the encoding.

JSON read: json.loads(text)

Parses syntax; add policy and contract checks.

JSON write: json.dumps(value, allow_nan=False)

Rejects nonfinite numbers while serializing.

Duplicate keys: object_pairs_hook=unique

Can reject repeated names at each object level.

JSON constants: parse_constant=reject

Can reject NaN and Infinity tokens.

Contract: type(value) is int

Excludes bool when an exact integer is required.

CSV read: csv.reader(stream, strict=True)

Parses a specified dialect; returns string cells.

CSV write: csv.writer(stream).writerows(rows)

Quotes fields; not spreadsheet formula mitigation.

File newline: open(path, newline="", encoding="utf-8")

Leaves newline handling to csv for real files.

TSV: delimiter="\t"

Specifies tabs plus the remaining csv dialect rules.

XML build: ET.Element("note")

Creates a node; set text without markup interpolation.

XML serialize: ET.tostring(root, encoding="unicode")

Escapes text; does not preserve original byte formatting.

XML find: root.find("a:note", {"a":"urn:atlas"})

Matches namespace URI and local name.

XML safety: ET.fromstring(authored_text)

Only trusted toy inputs in this pack.

TOML read: toml.loads(text)

Installed Tomli returns typed table values.

Schema boundary: validate(parsed_value)

A separate application step; no schema engine included.

Examples and practice

Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.

Data 01 - JSON round trip

Use a JSON serializer for quotes and escapes. Bytes require an encoding; this example uses UTF-8. Round trips preserve these JSON-compatible values, not every Python type.

import json
value = {"title": "Café", "minutes": 25, "done": False}
text = json.dumps(value, ensure_ascii=False, allow_nan=False)
encoded = text.encode("utf-8")
restored = json.loads(encoded.decode("utf-8"))
print(restored["title"], restored["minutes"], restored["done"])
print(restored == value)

Expected:

Café 25 False
True
Data 02 - Reject ambiguous JSON

Python json accepts duplicate names and nonstandard NaN by default. These hooks enforce a stricter local policy. Syntax validity still does not enforce a schema or prevent large/deep input resource costs.

import json
def reject_constant(value):
    raise ValueError("nonstandard number")
def unique(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate key")
        result[key] = value
    return result
for text in ['{"x":1,"x":2}', '{"x":NaN}', '{"x":}']:
    try:
        json.loads(text, object_pairs_hook=unique,
                   parse_constant=reject_constant)
    except ValueError:
        print("rejected")

Expected:

rejected
rejected
rejected
Data 03 - Read quoted CSV

CSV is a family of dialects, not a typed schema. Delimiter, quoting, headers, row width and encoding need agreement. A reader keeps numeric-looking cells as strings by default.

import csv, io
text = 'title,minutes\r\n"Read, then code",20\r\n"Say ""hello""",5\r\n'
rows = list(csv.reader(io.StringIO(text, newline=""), strict=True))
print(rows[1][0], rows[1][1])
print(rows[2][0], type(rows[2][1]).__name__)

Expected:

Read, then code 20
Say "hello" str
Data 04 - Write CSV safely

The writer handles embedded commas, quotes and newlines. When using real files pass encoding="utf-8" and newline="". CSV quoting does not neutralize spreadsheet formulas; these examples are parser exercises, not spreadsheet-safe exports.

import csv, io
rows = [["title", "note"], ["Café", 'Line 1\nLine "2"']]
buffer = io.StringIO(newline="")
csv.writer(buffer, lineterminator="\r\n").writerows(rows)
text = buffer.getvalue()
restored = list(csv.reader(io.StringIO(text, newline="")))
print(restored == rows)
print(restored[1][1].splitlines()[1])

Expected:

True
Line "2"
Data 05 - Choose a TSV dialect

TSV changes the delimiter, but quoting and newline conventions still need agreement. This toy uses Python csv default quote rules with a tab delimiter. Conversion to int is a separate application step.

import csv, io
text = "title\tminutes\nRead\t10\nCode\t20\n"
rows = list(csv.reader(io.StringIO(text, newline=""), delimiter="\t"))
if rows[0] != ["title", "minutes"] or any(len(r) != 2 for r in rows):
    raise ValueError("unexpected columns")
print(rows[1][0], rows[2][0])
print(sum(int(r[1]) for r in rows[1:]))

Expected:

Read Code
30
Data 06 - Build XML text

Construct a tree and serialize text to escape markup. Only tiny authored XML is parsed here. ElementTree is not a hardened parser for malicious data; no untrusted files, DTDs or external entities are accepted by this teaching workflow.

import xml.etree.ElementTree as ET
root = ET.Element("note", {"kind": "study"})
root.text = 'A & B < C'
text = ET.tostring(root, encoding="unicode")
restored = ET.fromstring(text)
print(text)
print(restored.text)

Expected:

<note kind="study">A &amp; B &lt; C</note>
A & B < C
Data 07 - XML namespaces and errors

Namespace identity is a URI, not a particular prefix. A parse error concerns well-formedness, not XSD validation. Explicit is not None avoids confusing an empty element with a missing one.

import xml.etree.ElementTree as ET
text = '<notes xmlns="urn:atlas"><note>Read</note></notes>'
root = ET.fromstring(text)
item = root.find("a:note", {"a": "urn:atlas"})
print(root.tag)
print(item.text if item is not None else "missing")
try:
    ET.fromstring("<note></notes>")
except ET.ParseError:
    print("malformed XML")

Expected:

{urn:atlas}notes
Read
malformed XML
Data 08 - Read TOML settings

Tested with installed Tomli 1.0.3, a private pip-vendored fallback on Python 3.9.6. The tomllib branch is for an already installed Python 3.11+ and was not executed here. No installation occurs. This covers a TOML 1.0 subset, not TOML 1.1.

try:
    import tomllib as toml
except ImportError:
    from pip._vendor import tomli as toml

text = '[study]\ntitle = "Café"\nminutes = 25\nactive = true\n'
value = toml.loads(text)
print(value["study"]["title"])
print(value["study"]["minutes"], value["study"]["active"])

Expected:

Café
25 True
Data 09 - Reject invalid TOML

Duplicate keys, uppercase True and unterminated strings violate these TOML rules. Syntactically valid settings still need an application contract.

try:
    import tomllib as toml
except ImportError:
    from pip._vendor import tomli as toml

for text in ['minutes = 1\nminutes = 2', 'active = True', 'title = "open']:
    try:
        toml.loads(text)
    except toml.TOMLDecodeError:
        print("invalid TOML")

Expected:

invalid TOML
invalid TOML
invalid TOML
Data exercise A - Validate JSON minutes

A small application contract requires exactly one key and an integer in range; bool is intentionally rejected even though it subclasses int in Python. This version uses default duplicate-key handling; combine example 02 hooks if duplicate rejection is required. A size cap alone is not comprehensive hostile-input protection.

import json

def load_minutes(text):
    if len(text.encode("utf-8")) > 256:
        raise ValueError("too large")
    value = json.loads(text)
    if not isinstance(value, dict) or set(value) != {"minutes"}:
        raise ValueError("keys")
    n = value["minutes"]
    if type(n) is not int or not 0 <= n <= 120:
        raise ValueError("minutes")
    return n

for text in ['{"minutes":20}', '{"minutes":true}', '{"minutes":121}']:
    try:
        print(load_minutes(text))
    except ValueError:
        print("invalid")

Expected:

20
invalid
invalid

Practice: Accept exactly the minutes key and an integer from 0 to 120. Reject booleans, extra keys and UTF-8 input longer than 256 bytes. State the duplicate-key policy.

Data exercise B - Convert CSV records

Row shape, header, nonblank labels and ASCII integer syntax are checked after parsing. This bounded toy totals at most ten records. csv.Error is a distinct possible syntax failure for malformed quoting.

import csv, io

def total(text):
    if len(text.encode("utf-8")) > 1024:
        raise ValueError("too large")
    rows = list(csv.reader(io.StringIO(text, newline=""), strict=True))
    if not rows or rows[0] != ["title", "minutes"] or len(rows) > 11:
        raise ValueError("header or row count")
    result = 0
    for row in rows[1:]:
        if len(row) != 2 or not row[0].strip() or not row[1].isascii() or not row[1].isdigit():
            raise ValueError("record")
        n = int(row[1])
        if n > 120:
            raise ValueError("range")
        result += n
    return result

print(total("title,minutes\nRead,10\nCode,20\n"))
try:
    total("title,minutes\nRead,-1\n")
except ValueError:
    print("invalid record")

Expected:

30
invalid record

Practice: Read a fixed two-column CSV dialect, validate up to ten records, and sum minutes. Reject negative values, extra columns and values over 120.

Data exercise C - Check XML structure

This application check is for tiny trusted authored strings only. It is not an XSD validator, a byte-preserving round trip or a safe untrusted XML entry point. Default ElementTree parsing can discard comments and processing instructions.

import xml.etree.ElementTree as ET

def title(text):
    root = ET.fromstring(text)
    children = list(root)
    if root.tag != "note" or root.attrib or len(children) != 1:
        raise ValueError("note structure")
    child = children[0]
    if child.tag != "title" or child.attrib or len(child):
        raise ValueError("title structure")
    if (root.text or "").strip() or (child.tail or "").strip():
        raise ValueError("mixed content")
    value = (child.text or "").strip()
    if not value:
        raise ValueError("empty title")
    return value

print(title("<note><title> Read </title></note>"))
try:
    title("<note><title /></note>")
except ValueError:
    print("invalid title")

Expected:

Read
invalid title

Practice: Require a note root with one nonblank title child, no attributes/nested elements, and no non-whitespace mixed text. Explain the trust boundary.

Prompt templates

These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.

Build a small example
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Return complete runnable files, expected output and a minimal verification procedure. Identify the format, parser version, trust boundary and schema limits. Do not execute parsed content.
Diagnose a failure
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Use the exact diagnostic or traceback. Explain one cause, one minimal correction and a regression check. Identify the format, parser version, trust boundary and schema limits. Do not execute parsed content.
Design boundary tests
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Include valid, invalid, empty and missing values. Distinguish proposed tests from executed evidence. Identify the format, parser version, trust boundary and schema limits. Do not execute parsed content.
Refactor with preserved behavior
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Show the before/after contract, preserve observed outputs and list changed assumptions. Identify the format, parser version, trust boundary and schema limits. Do not execute parsed content.
Document a contract
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Explain inputs, outputs, errors, encoding and environmental requirements, including unsupported cases. Identify the format, parser version, trust boundary and schema limits. Do not execute parsed content.
Review trust boundaries
For {language}, help me {goal}. Environment: {runtime}. Constraints: {constraints}. Inspect parsing, type assumptions and resource bounds. Explain what the checks do not guarantee. Identify the format, parser version, trust boundary and schema limits. Do not execute parsed content.

Further reading

Download the offline edition

Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON

Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.

Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.

Evidence and limits

Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.

The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.

Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.