Files and JSON
open gives a channel, and gets, read, puts, and close work on it. ztcl::json reads and writes JSON. This lesson keeps the notes of jot in notes.json.
The shell of this page has the file notes.json. A file that you write in the shell is in memory, and it goes away when you close the tab.
notes.json[{"text": "buy milk", "done": true}, {"text": "fix the bike #home", "done": false}]
Read a file
set f [open notes.json] opens the file and gives a channel name. set text [read $f] reads all of it, and close $f closes the channel. gets $f line reads one line and gives its length, or -1 at the end of the file.
Parse JSON
set notes [ztcl::json parse $text] makes Tcl values: an object is a dict, and an array is a list. Now the dict commands work: dict get [lindex $notes 1] text. ztcl::json get reads one value with no full parse: ztcl::json get $text 0 done.
Bad JSON is an error with its line and column: ztcl::json parse {[1,}.
Write JSON
A Tcl value has no visible type: 0 is a number, a string, and a boolean. encode needs a schema for the types. ztcl::json encode -schema {list {object {text string done bool}}} $notes gives the JSON of the notes. A guess with -auto makes a number of the canonical text of a number. 0 becomes a number, and 007 stays a string: ztcl::json encode -auto {text 007 done 0}.
Now save the notes. set f [open notes.json w] opens the file for writing and makes it empty. puts $f [ztcl::json encode -schema {list {object {text string done bool}}} $notes] writes one line. The channel keeps the text in a buffer, and close $f writes it to the file. Read the file again to check: set f [open notes.json]; set saved [read -nonewline $f]; close $f; set saved.
open with a adds to the end of a file, and r+ reads and writes. glob * gives the names of the files.
Files are a capability
In ztcl, files and channels are a capability. The ztcl program has them, and ztcl --root DIR keeps each path inside one folder. An app that embeds ztcl turns them on or keeps them off. Limits and capabilities tells how.
Reading code an agent wrote
- Each
openhas aclose, also on the path of an error. Look fortrywithfinally { close $f }. - A file name from input goes through a check, or the program runs with
--root. A name such as../../.ssh/configleaves the folder. - JSON goes out through
encodewith a schema. With-auto, a note with the text0ortruebecomes a number or a boolean. - A missing key of the JSON gives an error at
dict get. The code checks withdict exists.
Ask an agent
Write procs
jot::loadandjot::savethat keep the notes in notes.json. Useztcl::json encode -schemafor the types, andtrywithfinallyto close each channel.
Try this
- Read the file one line at a time with
getsin awhileloop. - Run
ztcl::json encode -schema {list {object {text string done bool}}} {{text x}}, and read the error. - Run
ztcl::json get $text 1 text.
The state of the shell at the start of this lesson
package require ztcl::json