Files, JSON and resource boundaries
Move between structured values and portable text safely.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 12 minutes; optional deep dive: 8 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
- Strings are sequences, not magic
- Dictionaries: model lookup, not position
- Errors are part of the contract
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Encode and decode JSON
- Use context managers for files
- Validate decoded structure
JSON is text, not a Python object
JSON is a text format for carrying values between programs. Decoding builds Python values from that text; encoding writes values back as text.
Understand first
A settings form or downloaded report needs portable data, not Python source code. Start with strings, dictionaries and booleans. The json module bridges those values to a format another program can read without running instructions.
Words you will see
- Decode
- Turn encoded text into usable values.
- Encode
- Represent values as text for storage or exchange.
- JSON object
- A JSON collection of string keys and values; it usually decodes to a Python dictionary.
Cross the text boundary deliberately
The quotes around the complete JSON make it a Python string. Inside it, double quotes mark JSON names and false is JSON's spelling. loads reads that string and creates a fresh dictionary containing the Python boolean False. The s in loads refers to a string; load instead reads from a file-like object.
Changing record changes the new dictionary, not the original text. dumps creates another string and translates True back to true. sort_keys=True chooses stable alphabetical key order for this display. It does not imply that business records must always be sorted.
Data is not executable code
Use json.loads, never eval, for JSON. eval runs Python expressions and exposes a code-execution boundary that a data reader does not need. JSON cannot represent every Python value: sets need a chosen conversion, and dictionary keys should be strings to avoid a changed round trip.
Malformed JSON raises JSONDecodeError. Successfully decoding a list instead of the expected object is a different problem, addressed next. This example uses a string already in the editor: it needs no host file, upload, network or installation. An empty string is invalid JSON; {} and [] are valid empty values.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
import jsonLoad the standard-library codec.
record = json.loads('{"name":"Ada","done":false}')Create a dictionary with name Ada and done False.
record["done"] = TrueReplace the decoded boolean.
print(json.dumps(record, sort_keys=True))Encode the changed dictionary, putting done before name and printing JSON true.
json.loads decodes JSON text to Python values; json.dumps produces JSON text. Do not use eval to read data. JSON true/false/null become Python True/False/None.
Conceptual format boundary, not a live execution trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- JSON textdone:false is text in the source string.
- Decoded valueloads creates a dictionary with Python False.
- Changed valueAssignment changes the dictionary entry to True.
- Encoded textdumps writes JSON true in a new string.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Keep the original boolean.
Try: Remove record["done"] = True.
The output contains false; decoding alone does not change it.
Observe a legitimate empty value.
Try: Replace the JSON string with "{}" and print record before the assignment.
The decoded value prints as {}; assigning done then creates its first entry.
Before you move on
A reader receives the JSON text "null". Does a successful decode guarantee a dictionary?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. It returns None. Decoding establishes valid syntax, not the application's required shape. Check that shape before indexing.
Close files even when work fails
A file-like stream is an object you can read or write. A with block gives a managed stream a clear lifetime and closes it even when the block fails.
Understand first
Real files hold resources as well as text. Close them promptly rather than waiting for cleanup at an unknown time. StringIO lets you learn the same read-position and context-management ideas inside browser Python without assuming a file exists.
Words you will see
- Stream
- An object that exposes sequential reading or writing.
- Cursor
- The current position where the next read or write starts.
- Context manager
- An object used by with to enter a scope and perform exit work, including cleanup.
Reads advance rather than restart
StringIO starts at the beginning of its supplied text. readline consumes through the first newline. strip removes surrounding whitespace from that returned string, not from the stream. read then consumes the remaining bread line. Repeating read at the end returns an empty string, not the full contents again.
with binds the stream to a name and closes it on leaving the block, including during an exception. The name still exists afterwards but reading the closed stream raises ValueError. Cleanup is not error recovery: closing a stream does not undo work or swallow the exception.
Choose a real-file mode only in a supported environment
For a real local file, open(path, encoding='utf-8') reads text. Mode w truncates existing content immediately; a appends; x requires a new file. Choosing an encoding determines how bytes map to characters. A binary stream instead handles bytes and has no text encoding argument.
The browser cannot open an arbitrary path on your laptop. These exercises use only in-memory streams. A browser virtual filesystem, if provided by the runner, is separate from host storage and is not a promise of persistence. A real filesystem lab must supply explicit paths and permissions; do not silently substitute sample data when a requested read fails.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
from io import StringIOImport a standard-library text stream.
with StringIO("tea\nbread\n") as stream:Create an owned stream with two lines.
first = stream.readline().strip()Read tea and advance past its newline.
rest = stream.read().strip()Read the remaining bread line.
print(first, rest)Display both saved strings while the stream is open.
print(stream.closed)After the context exits, display True.
Use with open(path, encoding='utf-8') as file for text reads. The context manager closes the file on exit. Choose read versus write/append mode carefully; opening with w truncates existing content.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Read at the end.
Try: Add print(repr(stream.read())) inside the block after print(first, rest).
It displays '' because the cursor has reached the end.
Rewind deliberately.
Try: Insert stream.seek(0) before rest = stream.read().strip().
rest now contains both lines, so printing it introduces an embedded newline.
Before you move on
If conversion raises inside a with block, may its caller safely keep reading that stream afterwards?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The context still closes it before the error propagates. Save required values before exit or open a new owned stream; do not reuse a closed resource.
Parsing is not schema validation
Schema validation checks whether decoded values have the fields and types your application needs. Valid JSON syntax alone does not establish that contract.
Understand first
A report total should not silently accept true as one minute or an absent field as zero. Check the boundary once, before the value enters calculation code. This requires dictionaries, comparisons and explicit exceptions.
Words you will see
- Schema
- The expected shape and meaning of data.
- Domain rule
- An application requirement beyond basic syntax, such as minutes being nonnegative.
- Boundary
- The point where external or less-trusted data enters an application.
Validate from the outside inward
First prove record is a dictionary so get is a meaningful operation. Next retrieve minutes. A missing key returns None here, which deliberately fails the integer check. type(minutes) is int excludes bool: in Python, isinstance(True, int) is True, although this report does not count booleans as durations.
The or condition short-circuits. If the type is wrong, Python does not attempt minutes < 0 on a string or None. If the type is right, the comparison checks its meaning. Explicit ValueError tells the caller to reject the report, rather than producing a plausible but false total.
Choose the contract, not the easiest default
Some products allow fractional minutes; then the validation and tests must say so. Some allow absent minutes; then a named default may be appropriate. This contract does neither. Checking truthiness would wrongly reject the valid value zero and might accept a nonempty string.
This is intentionally a small in-memory report, not a complete untrusted-upload validator. A production boundary also needs a size budget before decoding, allowed fields if relevant, and limits on nesting and records. JSON parsing and validation require work proportional to the data inspected; rejecting huge input after decoding does not recover the memory already spent.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
record = json.loads('{"minutes": 0}')Decode an object, retaining zero as an integer.
if not isinstance(record, dict):Reject the wrong outer shape before calling get.
minutes = record.get("minutes")Retrieve the field or None if absent.
if type(minutes) is not int or minutes < 0:Reject non-integers first, then negative integers.
print(minutes)Show the accepted zero without a fallback.
Valid JSON can still be the wrong shape, such as a number when you expect an object. Validate required fields and allowed types before accessing them. Keep file paths and maximum input sizes bounded when input is untrusted.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Test the boolean boundary.
Try: Change {"minutes": 0} to {"minutes": true}.
The explicit ValueError is visible; no total is fabricated.
Test a missing field.
Try: Change the JSON object to {}.
get returns None and the type branch rejects it before any numeric comparison.
Before you move on
Will {"minutes": true} pass this validator, and why not use isinstance alone?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
It fails. JSON true becomes Python True, whose exact type is bool. isinstance(True, int) would pass, so an exact int check expresses the stricter report rule.
Where this idea earns its place
Serialization connects values inside a program with a portable representation outside it. JSON is useful for simple cross-language data, while files provide persistence with their own lifetime and failure modes. Treat parsing, validation, computation and writing as separate boundaries so errors can be diagnosed precisely.
Follow the mechanism step by step
json.loads converts JSON text into Python values; json.dumps constructs text. Neither operation automatically enforces your domain schema. A valid JSON array may still be invalid where an object is required. with open acquires a file and closes it when the block exits, including an exception path.
Work through a concrete application
Decode a small study report, inspect its top-level type, validate each required field and only then aggregate. Keep the transformation callable with in-memory values so it can be tested without disk. Put file opening and output formatting around that transformation, with explicit encoding and a documented overwrite policy.
Failure cases and misleading shortcuts
eval is execution, not a JSON parser. Untrusted pickle is also unsafe because deserialization can execute code. A default value supplied for every missing field can hide an incompatible schema. Opening a destination in write mode truncates existing data before later validation or computation has succeeded.
Cost, ownership and alternatives
Reading an entire large JSON document usually retains both the text and decoded objects during part of processing. Line-oriented formats can stream when their framing permits it, but a normal JSON array cannot be split arbitrarily into independent lines. Bound input bytes and result cardinality rather than relying only on a file's apparent extension.
Verify the contract
Test malformed syntax separately from well-formed but wrong-shaped data. Include missing fields, wrong types, blank strings, zero/negative values and an oversized payload. Use temporary files for I/O tests and verify closure/rollback behaviour after an injected failure. Never test a destructive write against a user's original file.
Transfer question: How would you prevent a failed report calculation from destroying the previous report?
Complete validation and computation first when feasible, then write a temporary output in the destination filesystem and replace the old file only after success. Define cleanup and durability requirements; atomic replacement and guaranteed recovery after power loss are different promises.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Read a small report
Parse the JSON and sum the durations.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: decode a minute list
Decode report text without treating booleans or absent fields as durations.
The contract
- Input text is JSON; require a list of objects, each with a nonnegative exact int minutes field. Reject malformed JSON or any wrong shape/type/range with ValueError.
- Return the sum as an int; preserve record order and count repeated records separately. Empty list returns 0.
- Use only stdlib and in-memory text. Do not alter caller state or retain decoded records between calls.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- normal
assert decode_minutes('[{"minutes":2},{"minutes":3}]') == 5 - empty
assert decode_minutes('[]') == 0 - repeated and zero
assert decode_minutes('[{"minutes":0},{"minutes":2},{"minutes":2}]') == 4 - invalid types
for text in ('[{"minutes":true}]', '[{"minutes":"2"}]', '[{}]', '[{"minutes":-1}]', '[null]'): try: decode_minutes(text) except ValueError: continue raise AssertionError("Invalid duration accepted") - syntax and shape
for text in ("", "{", "{}", "null"): try: decode_minutes(text) except ValueError: continue raise AssertionError("Invalid report accepted") - caller and repeat calls
text = '[{"minutes":7}]' assert decode_minutes(text) == 7 and text == '[{"minutes":7}]' and decode_minutes("[]") == 0 and decode_minutes(text) == 7
Why not sum record.get('minutes', 0) immediately?
It masks missing fields and permits bool as an integer. Validate first. For b text characters and n records, parsing and validation inspect O(b + n) data, using O(b) decoded storage for ordinary bounded-depth reports.
Guided: encode a changed copy
Mark a report complete in encoded output without editing its owner's record.
The contract
- Input is a JSON-compatible dict with string keys; done may be absent or have any JSON-compatible value.
- Return JSON text for the same fields with done set to True, using sort_keys=True and default json.dumps spacing. Do not mutate input, including nested values.
- Empty input becomes {"done": true}. No files, network or retained mutable state; repeated calls are independent.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- normal
assert encode_done({"name":"Ada","done":False}) == '{"done": true, "name": "Ada"}' - empty
assert encode_done({}) == '{"done": true}' - overwrite only done
assert encode_done({"done":None,"n":0}) == '{"done": true, "n": 0}' - nested ownership
record = {"items":[{"x":1}]} child = record["items"] assert encode_done(record) == '{"done": true, "items": [{"x": 1}]}' and record == {"items":[{"x":1}]} and record["items"] is child - sorted keys
assert encode_done({"z":1,"a":2}) == '{"a": 2, "done": true, "z": 1}' - independent calls
first = {"done":False} assert encode_done(first) == '{"done": true}' and first == {"done":False} and encode_done({"x":2}) == '{"done": true, "x": 2}'
Why does shallow copying meet this ownership contract?
Only an outer key is replaced; nested values are read by the encoder, not edited. For b encoded characters and k outer keys, work is O(b + k log k) including key sorting, with O(b + k) additional storage.
Transfer: retain record locations
Change from summing a document to returning numbered values from a JSON Lines log.
The contract
- Input is text with one JSON value per physical line. Skip whitespace-only lines but retain physical one-based line numbers. Empty text yields a fresh empty list.
- Return a fresh list of (line_number, decoded_value) tuples in source order. Keep duplicates. Any nonblank malformed line raises ValueError.
- Use splitlines for this bounded in-memory exercise. Do not claim streaming memory, use files, or change caller data. Each call owns newly decoded mutable values.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- values
assert numbered_json('{"x":1}\n[2]\n') == [(1, {"x":1}), (2, [2])] - blank positions
assert numbered_json("\n0\n \nfalse\n") == [(2, 0), (4, False)] - empty
a = numbered_json("") b = numbered_json(" \n") assert a == [] and b == [] and a is not b - duplicates
assert numbered_json("2\n2\n") == [(1,2),(2,2)] - malformed
try: numbered_json("1\n{\n") except ValueError: pass else: raise AssertionError("Malformed nonblank row accepted") - decoded ownership
text = '{"x":[]}\n' a = numbered_json(text) b = numbered_json(text) assert a == [(1,{"x":[]})] and b == a and a is not b and a[0][1] is not b[0][1] a[0][1]["x"].append(1) assert b == [(1,{"x":[]})] and text == '{"x":[]}\n'
Why count before skipping blanks?
Diagnostics must name the source position, not the compacted result index. This bounded version splits and retains data: O(b) text work and storage plus decoded output, not a constant-memory streaming claim.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneStream large inputs
JSON Lines stores one complete JSON value on each line. It is a framing rule for records, not another name for a multiline JSON document.
Understand first
A long event log can be processed record by record instead of constructing a list of all events. Choose JSON Lines only when the producer promises that framing; a pretty-printed JSON array needs a different parser.
Words you will see
- Framing
- A rule that identifies where a record begins and ends.
- Streaming
- Processing pieces as they arrive instead of retaining the entire collection.
- Accumulator
- A small running result, here total.
Separate record boundaries from JSON syntax
Iterating the stream yields text lines. enumerate starts the record number at one so a failure can be reported meaningfully. loads receives one complete object per iteration. total keeps only the running integer, and the previous record can be released when replaced.
A newline escape inside a JSON string is written as backslash-n in the JSON text; it is not a physical record separator. Conversely, splitting a pretty-printed object across physical lines breaks this contract. A blank line is not a JSON value: reject it or explicitly document a skip policy rather than silently losing records.
Streaming has a budget, not magic constant memory
For a real streamed source, memory for this calculation depends on the largest line and decoded record, plus the total, rather than the number of records. A single enormous line can still exhaust memory. The teaching fixture text is already allocated, so this browser demonstration does not claim whole-program constant memory.
Accumulating all decoded records or every unique group removes the benefit. Bound line length and error samples at a production boundary, validate each record as in the previous section, and attach its number when rejecting it. Use one JSON array when atomic whole-document interchange is required, not arbitrary line splitting.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
text = '{"minutes": 2}\n{"minutes": 3}\n'Supply two complete records with explicit separators.
total = 0Start the running sum.
with StringIO(text) as stream:Own the in-memory source for this scope.
for number, row in enumerate(stream, 1):Consume one numbered line at a time.
record = json.loads(row)Decode that line, not the whole log.
total += record["minutes"]Add 2, then 3.
print(total)Display 5 after closing the stream.
Reading a whole file uses memory proportional to its size. Iterate text lines when the format allows it. JSON lines is a different framing contract from one large JSON array; do not assume normal JSON can be split on arbitrary line boundaries.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Append a valid zero record.
Try: Add {"minutes": 0}\n to the fixture text.
A third decode occurs but total remains 5.
Expose the row context.
Try: Add print(number, record["minutes"]) inside the loop.
The added lines are 1 2 and 2 3, making record numbering observable.
Before you move on
Can a three-line, indented JSON object be sent to this loop as one record?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The first physical line is incomplete JSON and decoding fails. Use json.load for a single document or have the producer emit one complete compact value per line.
Atomic updates and safety
A safe update prepares and validates replacement data before publishing it. Filesystem atomic replacement and durable storage are stronger, separate promises.
Understand first
Overwriting the only good report before a new report is complete risks partial state. Separate preparation from publication so validation failures leave the old value available. The browser example models that decision without claiming access to your filesystem.
Words you will see
- Publish
- Make a prepared result the current result.
- Atomic replacement
- A supported filesystem operation where observers see the old or the new file, not a partly replaced name.
- Durability
- Whether completed writes survive failures such as loss of power.
Build the candidate away from the current state
current starts as valid version-one text. dumps produces candidate without editing current. Decode candidate and check the version before assigning it. If encoding or validation raises, the publication line is never reached. Assignment here changes only a Python name in this run.
This protects against the modeled preparation failure, not all possible crashes. Two writers can still overwrite each other's changes without coordination. Keeping old versions or using a transaction may be better when several records must change together.
Translate the model honestly to real storage
A real local-file workflow writes a separately named sibling file on the same filesystem, closes it, and uses an appropriate replacement operation only after success. Follow the platform's permissions and cleanup rules. This course does not execute temporary-file creation or disk replacement in the browser example.
Atomic naming does not guarantee durable bytes after power loss; flushing and synchronisation requirements depend on the platform and needed guarantee. Nor does JSON provide a database transaction. Untrusted pickle is not a shortcut: loading it can execute code. JSON plus validation is appropriate for this small portable record.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
current = '{"version": 1}'Keep the old representation available.
candidate = json.dumps({"version": 2}, sort_keys=True)Encode the replacement independently.
verified = json.loads(candidate)Check the candidate's decoded representation.
if type(verified["version"]) is not int:Reject a version with the wrong exact type.
current = candidatePublish only after validation succeeds.
print(current)Show version two; no disk claim is implied.
A crash halfway through a write can leave partial data. For important local state, use a temporary file and an appropriate atomic replacement strategy. Untrusted pickle data can execute code and is not an alternative to JSON for public input.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Reject a candidate before publishing.
Try: Use {"version": "2"} in dumps.
Validation raises before publication; the reference output is not an actual successful run.
Observe both prepared states.
Try: Insert print(current, candidate) immediately before verified = json.loads(candidate).
The added display shows old version one alongside candidate version two.
Before you move on
If preparing version three raises before current = candidate, what remains current? Is it durable?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Version one remains bound in this program. That says nothing about disk durability: the example has not written to disk at all.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.