Files and data formats ====================== Move a small model between readable text, quoted CSV, JSON, and UTF-8 files. Build an explicit import pipeline, preserve good data when input is malformed, and save fresh snapshots without overwriting old ones. Squeak 6.1 build 23976, 64-bit, clean official Linux image Install the complete support application once, then run nine small independent experiments. The focused methods beside each stage explain the implementation; full file-in sources include all UI and helper methods. Workspace blocks are expressions; chunk-format .st class files are for File List → fileIn. INSTALLATION 1. Use a separate learning image based on Squeak 6.1 build 23976. 2. Before filing in, Print it: Smalltalk at: #Json ifAbsent: [nil]. It must answer the Json class in this tested image. 3. Download LQDataLab.st and choose fileIn in the File List. This installs LQDataLab and LQDataJSONReader. 4. File in LQDataLabTests.st before stage 9. Keep source and data files separate. 5. To open the final app at any time, Do it: LQDataLab open. FILE TYPES LQDataLab.st: chunk-format class source; File List -> fileIn. LQDataLabTests.st: SUnit test class source; file in after the application. files-stage-NN.st: Workspace expression; open as text, select all, Do it. Each returns an app or Inspector window. FilesExercises-Solutions.st: solution methods/classes; file in after attempting the exercises. files-exercises-check.st: Workspace assertions; select all and Do it after solutions. FINAL APP LQDataLab open TEST SUITE LQDataLabTests suite run Verified: 21 tests passed. CSV quoting and embedded line breaks; malformed CSV/JSON/UTF-8; Unicode surrogate pairs; immutable record copies; validated imports; fresh snapshots; refusal to overwrite; staging collisions; simulated staging verification failure; repeat-save/reload. MEDIA Screenshots are native Morphic imageForm captures produced by the real Squeak VM. GIFs assemble those native frames from scripted message sequences. They are not mouse recordings, browser re-creations, or performance benchmarks. All media are delivered on the companion lesson page. This ZIP contains this lesson’s sources and guide only. STAGE 1: Start with records, not file names ----------------------------------------------------------------- Build a tiny data workbench for pairs of name and score. A record is a two-element Array: a String and an Integer from 0 through 10. The model begins with Ada, Lovelace; Grace "Amazing" Hopper; and café. These names deliberately exercise commas, quotes, and non-ASCII text. The model owns its records and returns copies. Formatting, parsing, validation, file operations, and Morphic display are separate methods. That separation lets us test corrupt input without clicking through a dialog. No file is created by opening the app. Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage. RUNNABLE CHECKPOINT | lab | lab := LQDataLab open. lab stage: 1. lab records size = 3 ifFalse: [self error: 'Expected three starter records']. lab EXPECTED A native window shows three records and “No files written yet”. Scores are 9, 10, and 7. WATCH FOR The displayed text is a view. It is deliberately read-only; this lesson is about interchange, not editing widgets. TRY IT Change a copy returned by records in an Inspector. The live model should stay unchanged. Browser · LQDataLab · instance side · Accept this method initialize super initialize. records := {{'Ada, Lovelace'. 9}. {'Grace "Amazing" Hopper'. 10}. {'caf', (Unicode value: 233) asString. 7}}. status := 'Ready: three records in memory'. preview := ''. stage := 1 Browser · LQDataLab · instance side · Accept this method records ^ records collect: [:row | {row first copy. row second}] STAGE 2: Turn characters into UTF-8 bytes ----------------------------------------------------------------- A String contains characters; a file stores bytes. ASCII characters use one byte in UTF-8, while é uses the two bytes 195 and 169. The source constructs the character from its Unicode value so the tutorial source itself remains plain ASCII. The supplied encoder writes UTF-8 without a byte-order mark and normalizes line endings to LF. Its strict decoder accepts an optional leading BOM, preserves an interior U+FEFF, and rejects invalid continuations, overlong encodings, surrogate code points, and values above U+10FFFF. This explicit codec avoids the permissive behavior of some image converters. Keep binary I/O and character decoding as distinct operations. Using a text stream with an unknown default converter can silently apply a different encoding. The helper methods are deliberately explicit so a round trip means what you think it means. Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage. RUNNABLE CHECKPOINT | lab text bytes | lab := LQDataLab open. lab stage: 2; showText. text := 'caf', (Unicode value: 233) asString. bytes := lab encodedTextBytes: text. bytes = #[99 97 102 195 169] ifFalse: [self error: 'Unexpected UTF-8 bytes']. (lab decodeUTF8Bytes: bytes) = text ifFalse: [self error: 'Round trip failed']. lab report: 'UTF-8: cafe-with-accent = 4 characters, 5 bytes; round trip passed'. lab EXPECTED The café sample has 4 characters and 5 UTF-8 bytes. Both assertions pass; no files are written. WATCH FOR A .txt suffix says nothing about a file’s actual encoding. Agree on an encoding with the other application. TRY IT Print (lab decodeUTF8Bytes: #[192 175]) in a protected error block. The invalid, overlong sequence must be rejected. Browser · LQDataLab · instance side · Accept this method encodedTextBytes: aString "Encode Unicode scalars as UTF-8 without a BOM, using LF line endings." | normalized | normalized := aString withLineEndings: String lf. ^ ByteArray streamContents: [:out | normalized do: [:character | | code | code := character asUnicode. (code isNil or: [code < 0 or: [code > 1114111 or: [code between: 55296 and: 57343]]]) ifTrue: [self error: 'The sample contains an invalid Unicode scalar']. code < 128 ifTrue: [out nextPut: code] ifFalse: [ code < 2048 ifTrue: [ out nextPut: 192 + (code bitShift: -6); nextPut: 128 + (code bitAnd: 63)] ifFalse: [ code < 65536 ifTrue: [ out nextPut: 224 + (code bitShift: -12); nextPut: 128 + ((code bitShift: -6) bitAnd: 63); nextPut: 128 + (code bitAnd: 63)] ifFalse: [ out nextPut: 240 + (code bitShift: -18); nextPut: 128 + ((code bitShift: -12) bitAnd: 63); nextPut: 128 + ((code bitShift: -6) bitAnd: 63); nextPut: 128 + (code bitAnd: 63)]]]]] STAGE 3: Write and parse quoted CSV ----------------------------------------------------------------- CSV is a state machine, not a simple split on commas. The name Ada, Lovelace must be one field. A literal quote inside a quoted field is doubled, so Grace "Amazing" Hopper is written with doubled internal quotes. This lesson chooses a specific dialect: a required name,score header, comma separators, double-quoted string fields, LF output, and LF, CR, or CRLF input. Embedded newlines inside quotes are allowed. Spaces outside quotes are data. A closing quote must be followed by a separator, line ending, or end of input. The parser first creates rows of Strings. Then parseCSV: checks the header, requires exactly two fields, converts a digits-only score, and validates the complete record array. A semicolon-separated export needs an explicit dialect change; guessing from an arbitrary file is outside this small parser. Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage. RUNNABLE CHECKPOINT | lab | lab := LQDataLab open. lab stage: 3; showCSV. (lab parseCSV: lab csvText) = lab records ifFalse: [self error: 'CSV round trip failed']. lab report: 'CSV round trip passed: comma and quotes stayed inside the names'. lab EXPECTED The preview shows the header and three rows. Ada’s comma is quoted; Grace’s embedded quotes are doubled. Reading the CSV returns the original records. WATCH FOR Always quoting a field does not make arbitrary CSV safe to open as spreadsheet formulas. These tutorial names are fixed examples; production spreadsheet exports need a documented formula-handling policy. TRY IT Read the complete csvRows: method in the download. Follow its four states: start, bare, quoted, and afterQuote. Browser · LQDataLab · instance side · Accept this method csvField: aString "Always quote strings. A quote inside a field is doubled." ^ String streamContents: [:out | out nextPut: $". aString do: [:ch | ch = $" ifTrue: [out nextPut: $"]. out nextPut: ch]. out nextPut: $"] Browser · LQDataLab · instance side · Accept this method csvText ^ String streamContents: [:out | out nextPutAll: 'name,score'; lf. records do: [:row | out nextPutAll: (self csvField: row first); nextPut: $,; print: row second; lf]] Browser · LQDataLab · instance side · Accept this method parseCSV: aString | rows candidates | aString size > 100000 ifTrue: [self error: 'CSV text is too large']. rows := self csvRows: aString. (rows notEmpty and: [rows first = #('name' 'score')]) ifFalse: [self error: 'CSV header must be name,score']. candidates := rows allButFirst collect: [:row | | scoreText | row size = 2 ifFalse: [self error: 'CSV row needs exactly two fields']. scoreText := row second. (scoreText notEmpty and: [scoreText allSatisfy: [:ch | ch between: $0 and: $9]]) ifFalse: [self error: 'CSV score must contain decimal digits only']. {row first. scoreText asNumber}]. ^ self validateRecords: candidates STAGE 4: Validate all rows, then replace the model ----------------------------------------------------------------- An import has two phases: build a candidate value, then commit it. The importer does not append records while it parses. If the last row is invalid, the earlier valid rows never leak into the model. Our schema is intentionally small: at most 1,000 records; each record has exactly two fields; names contain 1–120 characters; scores are integers from 0 through 10. These are application rules, separate from the CSV or JSON syntax. The functions return fresh arrays so imported data cannot accidentally alias mutable caller data. Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage. RUNNABLE CHECKPOINT | lab | lab := LQDataLab open. lab stage: 4. lab importGoodSample ifFalse: [self error: 'Import should succeed']. lab records = #(('Imported, safely' 8)) ifFalse: [self error: 'The committed records are wrong']. lab EXPECTED The model is replaced by exactly one record: Imported, safely with score 8. The comma remains part of the name. WATCH FOR The transaction here is an in-memory replacement after validation. It is not a database transaction and does not promise isolation against arbitrary external writers. TRY IT Change the sample’s score from 8 to 99. The importer should return false and keep the three original records. Browser · LQDataLab · instance side · Accept this method validateRecords: candidates "Return fresh validated records. Do not mutate the live model here." (candidates isArray and: [candidates size <= 1000]) ifFalse: [self error: 'Expected an array of at most 1000 records']. ^ candidates collect: [:row | | name score | (row isArray and: [row size = 2]) ifFalse: [self error: 'Each record needs a name and score']. name := row first. score := row second. (name isString and: [name size between: 1 and: 120]) ifFalse: [self error: 'Name must contain 1 to 120 characters']. (score isInteger and: [score between: 0 and: 10]) ifFalse: [self error: 'Score must be an integer from 0 to 10']. {name copy. score}] Browser · LQDataLab · instance side · Accept this method importCSV: aString | replacement | [replacement := self parseCSV: aString] on: Error do: [:error | ^ self report: 'Import rejected: ', error messageText]. records := replacement. status := 'CSV imported: ', records size printString, ' valid records'. preview := self csvText. self refresh. ^ true STAGE 5: Use JSON with a versioned schema ----------------------------------------------------------------- JSON carries explicit arrays, objects, strings, booleans, null, and numbers. Our document has version and records keys. The version field gives future code a clear place to reject or migrate a changed format. The tested Squeak 6.1 image includes Json. LQDataJSONReader subclasses it to reject raw control characters in strings and validate Unicode surrogate escapes. The reader sets ctorMap: nil and dictionaryClass: Dictionary, so the import returns ordinary data rather than constructing application objects. No imported text is evaluated as Smalltalk. Object-key order is not significant. Json may render records before version, and integral numeric spellings may normalize to an Integer. Validate the parsed value. Unknown object properties are ignored by this small schema; this is not a full JSON Schema engine or a parser hardened for unbounded hostile nesting. Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage. RUNNABLE CHECKPOINT | lab | lab := LQDataLab open. lab stage: 5; showJSON. (lab parseJSON: lab jsonText) = lab records ifFalse: [self error: 'JSON round trip failed']. lab report: 'JSON round trip passed: version 1 and all three records validated'. lab EXPECTED The preview contains a JSON object with version 1 and three records. Escaped quotes and Unicode text survive the round trip. WATCH FOR Json is the class tested here. Other Squeak images may have different JSON packages or APIs. Check the class before filing in this lesson; do not replace it blindly with an unrelated JSON library. TRY IT Print Smalltalk at: #Json ifAbsent: [nil]. If it is nil, use the tested Squeak 6.1 release or adapt the importer to the documented parser in your image. Browser · LQDataLab · instance side · Accept this method jsonText | document | document := Dictionary new. document at: 'version' put: 1; at: 'records' put: self records. ^ Json render: document Browser · LQDataLab · instance side · Accept this method parseJSON: aString | document | aString size > 100000 ifTrue: [self error: 'JSON text is too large']. document := (LQDataJSONReader new ctorMap: nil; dictionaryClass: Dictionary; yourself) readFromString: aString withBlanksTrimmed. (document isKindOf: Dictionary) ifFalse: [self error: 'Expected a JSON object']. ((document at: 'version' ifAbsent: [nil]) isInteger and: [(document at: 'version') = 1]) ifFalse: [self error: 'Expected format version 1']. ^ self validateRecords: (document at: 'records' ifAbsent: [self error: 'Missing records']) STAGE 6: Stage a complete file before publishing it ----------------------------------------------------------------- The first save creates a fresh LearnSqueak-DataLab-N directory under FileDirectory default. The code chooses an unused directory name and never adopts an existing folder. Each Save new JSON creates a new numbered snapshot, so repeated saves preserve earlier snapshots. safeSaveText:named: encodes the whole String, writes a .pending file in the same directory, flushes and closes it with ensure:, reads the bytes back, and checks equality before renaming it to the final name. A collision is reported instead of opening an overwrite dialog. On a normal failed staging operation, the temporary file owned by this attempt is removed. This strategy prevents a partially written file from being presented as a completed snapshot in the normal flow. It does not promise crash durability, atomic overwrite on every filesystem, symlink isolation, or safe concurrent access by arbitrary writers. For this lesson use the fresh tutorial-owned directory. Production replacement needs a platform-specific policy for backup, rename, locking, and recovery. Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage. RUNNABLE CHECKPOINT | lab | lab := LQDataLab open. lab stage: 6. lab saveJSONSnapshot ifFalse: [self error: 'Save failed']. (lab parseJSON: (lab decodeUTF8Bytes: (lab readBytesNamed: lab lastSaved))) = lab records ifFalse: [self error: 'Saved snapshot did not round trip']. lab EXPECTED A new tutorial folder contains records-1.json. The saved bytes decode and validate to the same records. No .pending file remains. WATCH FOR Do not use forceNewFileNamed: for a user-selected destination without an explicit overwrite policy. It can truncate an existing file before the write succeeds. TRY IT Try saving changed text as records-1.json in the same model. It must reject the collision and preserve the original bytes. Browser · LQDataLab · instance side · Accept this method prepareDirectory "A fresh, tutorial-owned directory. Never adopt or clear an existing directory." | base prefix leaf index | directory ifNotNil: [^ directory]. base := FileDirectory default. prefix := 'LearnSqueak-DataLab-'. index := 1. [leaf := prefix, index printString. (base directoryExists: leaf) or: [base fileExists: leaf]] whileTrue: [index := index + 1]. base createDirectory: leaf. directory := base directoryNamed: leaf. ^ directory Browser · LQDataLab · instance side · Accept this method safeSaveText: aString named: leaf "Write a new snapshot. Never overwrite an existing destination. A same-directory rename is used only after verifying staged bytes. This is not a crash-durability guarantee or a general concurrent file service." | bytes temporary stream | self prepareDirectory. self validateLeaf: leaf. ((directory fileExists: leaf) or: [directory directoryExists: leaf]) ifTrue: [self error: 'Snapshot already exists; choose a new name']. temporary := leaf, '.pending'. ((directory fileExists: temporary) or: [directory directoryExists: temporary]) ifTrue: [self error: 'Staging name already exists; choose a new name']. bytes := self encodedTextBytes: aString. [ stream := FileStream newFileNamed: (directory fullNameFor: temporary). stream ifNil: [self error: 'Staging file could not be created']. [stream binary; nextPutAll: bytes; flush] ensure: [stream close]. (self readBytesNamed: temporary) = bytes ifFalse: [self error: 'Staged bytes did not verify']. ((directory fileExists: leaf) or: [directory directoryExists: leaf]) ifTrue: [self error: 'Destination changed while saving']. [directory rename: temporary toBe: leaf] on: ReplaceExistingFileException do: [:error | self error: 'Destination changed while saving']. ((directory fileExists: leaf) and: [(directory fileExists: temporary) not]) ifFalse: [self error: 'Snapshot rename did not complete'] ] on: Error do: [:error | (directory fileExists: temporary) ifTrue: [directory deleteFileNamed: temporary]. error pass]. lastSaved := leaf. ^ directory fullNameFor: leaf STAGE 7: Reject malformed data without losing good state ----------------------------------------------------------------- A parse error, an encoding error, and a schema error are different failures, but none should replace valid live data. The supplied example has a valid first row followed by score 99. The complete import is rejected, and all three original records remain. Errors become a readable status message at the application boundary. The lower-level parser still signals Error, which makes it testable and composable. The file reader closes the stream even when a size check fails. The limit is 1 MiB of bytes on disk and 100,000 characters in each CSV or JSON parse call. The tests also exercise an unclosed CSV quote, garbage after the JSON document, unescaped JSON controls, malformed UTF-8, and unpaired surrogate escapes. Bounded input is useful, but this teaching parser is not a complete defense against hostile deeply nested JSON. Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage. RUNNABLE CHECKPOINT | lab before | lab := LQDataLab open. lab stage: 7; showJSON. before := lab records. lab rejectBadSample ifTrue: [self error: 'Invalid data was accepted']. lab records = before ifFalse: [self error: 'Failed import changed the model']. lab EXPECTED The status says the score must be 0–10. The preview and model still contain all three original records; the valid first candidate row was not committed. WATCH FOR Catching an error is not enough if you already changed the model. Keep the commit assignment after all parsing and validation. TRY IT Replace the bad JSON with a syntactically broken document. Confirm that the same keep-old-data rule still holds. Browser · LQDataLab · instance side · Accept this method importJSON: aString | replacement | [replacement := self parseJSON: aString] on: Error do: [:error | ^ self report: 'Import rejected: ', error messageText]. records := replacement. status := 'JSON imported: ', records size printString, ' valid records'. preview := self jsonText. self refresh. ^ true Browser · LQDataLab · instance side · Accept this method readBytesNamed: leaf | stream | directory ifNil: [self error: 'Prepare the tutorial directory first']. self validateLeaf: leaf. stream := FileStream readOnlyFileNamed: (directory fullNameFor: leaf). stream ifNil: [self error: 'File could not be opened']. ^ [stream binary. stream size > 1048576 ifTrue: [self error: 'File exceeds 1 MiB']. stream upToEnd] ensure: [stream close] STAGE 8: Reload a verified snapshot and test repeat saves ----------------------------------------------------------------- The application remembers the leaf name of its last successful snapshot. Reload reads bytes from that tutorial directory, decodes UTF-8, validates JSON, and only then replaces the model. This checkpoint saves twice, imports a different valid sample into memory, then reloads the last snapshot. It demonstrates the boundary between live state and persisted state. Saving a Squeak image is a separate operation: an image snapshot preserves the running object memory, while these JSON files exchange a small portable data format. Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage. RUNNABLE CHECKPOINT | lab original | lab := LQDataLab open. lab stage: 8. original := lab records. lab saveJSONSnapshot; saveJSONSnapshot; importGoodSample. lab loadLastSnapshot ifFalse: [self error: 'Reload failed']. lab records = original ifFalse: [self error: 'Reload did not restore the snapshot']. lab report: 'Reloaded records-2.json: original three records restored'. lab EXPECTED Two separate JSON files exist. The live model returns to the original three records after reload, and the last snapshot is records-2.json. WATCH FOR The saved file is the model at save time. Editing a JSON file outside Squeak does not alter the live model until you explicitly reload. TRY IT Save once more after a successful import. Observe that the new snapshot preserves the imported model while previous snapshots remain available. Browser · LQDataLab · instance side · Accept this method saveJSONSnapshot | index leaf | self prepareDirectory. index := 1. [leaf := 'records-', index printString, '.json'. (directory fileExists: leaf) or: [directory directoryExists: leaf]] whileTrue: [index := index + 1]. [self safeSaveText: self jsonText named: leaf] on: Error do: [:error | ^ self report: 'Save failed: ', error messageText]. status := 'Saved new UTF-8 snapshot: ', leaf. preview := self jsonText. self refresh. ^ true Browser · LQDataLab · instance side · Accept this method loadLastSnapshot | text | lastSaved ifNil: [^ self report: 'Save a snapshot first']. [text := self decodeUTF8Bytes: (self readBytesNamed: lastSaved)] on: Error do: [:error | ^ self report: 'Read failed: ', error messageText]. ^ self importJSON: text STAGE 9: Run the regression tests and extend the workbench ----------------------------------------------------------------- File in LQDataLabTests.st after the application source. Run the suite from a Workspace or select LearnSqueak-Files-Tests in the Test Runner. The suite covers round trips, field quoting, malformed inputs, Unicode, preservation of prior data, no-overwrite behavior, staging collisions, and simulated verification failure. Each file test creates its own fresh tutorial directory. tearDown removes only that directory’s test files and the empty directory. The tests do not touch personal files or the sample directories from your manual experiments. The three exercises below build on these same boundaries: compute a total, export a filtered CSV without changing the model, and load a named JSON file through the existing validation path. Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage. RUNNABLE CHECKPOINT | lab result | result := LQDataLabTests suite run. lab := LQDataLab open. lab stage: 9; showCSV. lab report: 'SUnit: ', result passedCount printString, ' passed / ', result runCount printString, ' run'. (result failures isEmpty and: [result errors isEmpty]) ifFalse: [self error: 'Open the Test Runner to inspect failures']. lab EXPECTED 21 tests run and 21 pass in the tested image. The native workbench reports the suite counts. WATCH FOR A green suite verifies the listed cases in the tested image. It does not establish universal CSV dialect support or crash-safe file replacement. TRY IT Introduce a deliberate parser mistake, run the relevant test, then restore the source and return to green. EXERCISES 1. Compute a score total Add scoreTotal to LQDataLab using inject:into:. Do not format and then reparse the preview. Expected: The initial total is 26. Importing only a record with score 8 changes the total to 8. Solution (attempt the exercise first): Browser · LQDataLab · instance side · exercise solutions protocol · Accept the one method. Alternatively, file in FilesExercises-Solutions.st. scoreTotal ^ records inject: 0 into: [:total :row | total + row second] Check: Workspace · select the entire check block · Print it (Ctrl/Cmd+P), after installing the solution. LQDataLab new scoreTotal = 26 Expected check result: true 2. Export high scores without changing records Add highScoresCSV. Include only scores at least 9, keep the header, and use csvField: so commas and quotes remain correct. Expected: Parsing the export returns the first two initial records. The model still has three records. Solution (attempt the exercise first): Browser · LQDataLab · instance side · exercise solutions protocol · Accept the one method. Alternatively, file in FilesExercises-Solutions.st. highScoresCSV ^ String streamContents: [:out | out nextPutAll: 'name,score'; lf. (records select: [:row | row second >= 9]) do: [:row | out nextPutAll: (self csvField: row first); nextPut: $,; print: row second; lf]] Check: Workspace · select the entire check block · Print it (Ctrl/Cmd+P), after installing the solution. | lab before | lab := LQDataLab new. before := lab records. {(lab parseCSV: lab highScoresCSV) = (before first: 2). lab records = before} Expected check result: #(true true) 3. Import a named snapshot transactionally Add loadJSONNamed: for simple leaf names in the existing tutorial directory. Reuse the byte reader, strict decoder, and importJSON:; do not mutate records directly. Expected: A malformed file returns false and leaves all records untouched. A valid file replaces the model only after validation. Solution (attempt the exercise first): Browser · LQDataLab · instance side · exercise solutions protocol · Accept the one method. Alternatively, file in FilesExercises-Solutions.st. loadJSONNamed: leaf | text | [text := self decodeUTF8Bytes: (self readBytesNamed: leaf)] on: Error do: [:error | ^ self report: 'Read failed: ', error messageText]. ^ self importJSON: text Check: Workspace · select the entire check block · Print it (Ctrl/Cmd+P), after installing the solution. | lab before rejected unchanged loaded | lab := LQDataLab new. before := lab records. [ lab safeSaveText: '{"version":1,"records":[["Bad",99]]}' named: 'bad.json'. rejected := (lab loadJSONNamed: 'bad.json') not. unchanged := lab records = before. lab safeSaveText: '{"version":1,"records":[["Good",8]]}' named: 'good.json'. loaded := lab loadJSONNamed: 'good.json'. {rejected. unchanged. loaded. lab records = #(('Good' 8))} ] ensure: [ lab directory ifNotNil: [:owned | owned fileNames do: [:leaf | owned deleteFileNamed: leaf]. FileDirectory default deleteDirectory: owned localName]] Expected check result: #(true true true true) CLEANUP Close tutorial windows. Keep or remove only the LearnSqueak-DataLab-N directories you created for this lesson. The SUnit/exercise checks clean up only their own fresh directories. Saving your image keeps the installed classes; the source files let you recreate them. LIMITS No file chooser or personal-directory scan; only a newly created tutorial-owned folder. Snapshots refuse replacement. Same-directory rename is not a guarantee of crash durability or arbitrary concurrent writer safety. The CSV dialect is fixed. JSON uses the tested image’s Json plus strict string handling; deeply hostile nesting is outside this teaching example. REFERENCES Squeak official downloads — https://squeak.org/downloads/ The tested image family; local source inspection verified Json, FileDirectory, FileStream, and Morphic APIs. RFC 4180: CSV format conventions — https://www.rfc-editor.org/info/rfc4180/ Quoted fields, doubled quotes, headers, and line ending conventions. This lesson explicitly uses a small LF-output dialect. RFC 8259: JSON — https://www.rfc-editor.org/info/rfc8259/ JSON data syntax and interoperability. Application schema validation remains a separate step. RFC 3629: UTF-8 — https://www.rfc-editor.org/info/rfc3629/ UTF-8 byte sequences and valid Unicode ranges.