Understand the idea
A problem you can recognise
Your planner needs to share session data with another program. A Python dictionary is useful while Python is running, but another application needs an agreed text representation. JSON provides that interchange format; it is not a promise that the received data is valid for your planner.
We will separate three events that are often confused: parsing text, validating its meaning, and saving data somewhere that will outlive the current exercise.
Understand the idea
Understand the idea
JSON is a text data format, not executable Python source. json.loads parses JSON text into Python values; json.dumps serialises compatible values into JSON text. JSON true, false and null map to Python True, False and None. Object keys are text, and JSON does not preserve arbitrary Python object types.
Parsing is not complete validation. A syntactically valid JSON document can still have missing fields, unexpected types or unreasonable sizes. Check the shape and domain constraints before treating data as a trusted record. Never use eval to parse text received from a user or a remote system. The JSON parser is built for this job and does not need to execute source code.
File access also has an environment boundary. The practice interpreter uses an isolated virtual filesystem and does not promise persistence after a session or reload. To demonstrate the file interface without changing any real files, these examples use io.StringIO. Its with statement shows a context-managed text stream that is closed afterward. A production program using real paths would additionally need explicit encoding, path boundaries, size limits and an appropriate storage lifecycle.
See how it works
Example 1: Read JSON data
PYTHON exampleRead the code, then try a change.
Try this example
import json
record = json.loads('{"subject":"Python","minutes":30,"done":true}')
print(record["subject"])
print(record["done"])
Expected output:
ReferenceCompare this with the explanation.
Python
True
The JSON boolean becomes a Python bool. The parsed dictionary can be queried with normal key access, but a real application should still verify required keys and value types.
See how it works
Example 2: Serialise predictably
PYTHON exampleRead the code, then try a change.
Try this example
import json
record = {"minutes": 30, "done": False}
print(json.dumps(record, sort_keys=True))
Expected output:
ReferenceCompare this with the explanation.
{"done": false, "minutes": 30}
dumps creates a JSON string. Sorting keys makes this example’s output stable; it does not change the dictionary’s meaning or add validation.
See how it works
Example 3: Read a bounded text stream
PYTHON exampleRead the code, then try a change.
Try this example
from io import StringIO
with StringIO("Python\nHTML\n") as stream:
first = stream.readline().strip()
second = stream.readline().strip()
print(first)
print(second)
print(stream.closed)
Expected output:
ReferenceCompare this with the explanation.
Python
HTML
True
The stream contains fixed in-memory text, not a persistent external file. readline reads one line at a time, and leaving the context closes the stream.
Understand the idea
Think through the important decisions
After json.loads returns, inspect the resulting Python value. A syntactically valid JSON value might be a list, a number or an object, not necessarily the record your code expects. Parsing success therefore does not establish that subject and minutes fields exist or satisfy your rules.
When serialising, identify which values can be represented by the chosen interchange format. JSON objects use string keys, and values such as arbitrary class instances do not automatically acquire a safe, meaningful JSON representation. Keep your example records small and explicit.
A file-like object can demonstrate reading and writing within a bounded exercise. That is different from saving a user's progress permanently across devices. In this course's browser runtime, printing JSON text and reading an in-memory stream are useful language exercises without requiring access to a real user's files or an external database.
Check your understanding
Check the reasoning
JSON parsing constructs data, not executable source, and parsed records still need validation.
A matching screenshot or output is one check, not proof that a program is correct for all inputs. Change one input, predict the new result and run again. If the result differs, find the first instruction where your prediction stops matching the program state. Keep that small case as a regression check when you fix the cause.
Spot the mistake
The mistake worth understanding
Do not use eval to read JSON. Treat received text as data, and handle parsing failures honestly. Also do not report "saved permanently" because a temporary in-memory write succeeded; persistence is a separate capability with its own storage rules.
Your turn
Independent practice
Parse a small JSON revision record and check that minutes is an integer in a reasonable positive range. Serialise an updated record without executing any input as Python. Explain why the browser does not provide durable file storage here.
Your turn
Practice hint
Use json.loads and explicit isinstance/range checks. Keep any text-stream demonstration in StringIO.
Your turn
Try a different case
Parse one valid session, then validate its required fields. Try valid JSON with the wrong structure and explain why it must still be rejected. Finally, describe exactly where your exercise's data exists after the program ends.