Lesson 9.1 · 9 min
Messages become JSON
Chatterbox saves its history in a format only Chatterbox understands. JSON is a plain-text format that every language can read, and it is also how programs talk to a model. This lesson saves the history as JSON, using a crate called serde and the traits from lesson 8.4, and Chatterbox writes no translating code by hand.
Adds to ChatterboxThe history is saved as JSON.
Why JSON
Since lesson 8.2, chatterbox.log holds lines like you: hello. It works, but it is a format we made up. No other program knows it. Every new thing we want to store (a time, say) means new splitting code in from_lines. And one awkward character, such as a colon-and-space inside an author name, would split a line in the wrong place.
Almost every program that stores or sends data as text uses JSON instead: curly braces for a record, square brackets for a list, quoted names for fields. A Chatterbox message as JSON looks like {"author":"you","text":"hi"}, and the whole history is a list of those in square brackets. It is also the format a model's service speaks, which matters in the very next lesson.
Writing a value down as text is called serializing. Reading text back into a value is deserializing.
Crates: code other people wrote
Rust's standard library does not know JSON. A crate is a package of Rust code someone else wrote, and you ask for it by name in Cargo.toml, the file you met in lesson 1.2. Two crates do the work here: serde knows how to turn Rust values into and out of formats, and serde_json teaches it the JSON format.
From inside your project folder, cargo add serde --features derive and cargo add serde_json add both lines to Cargo.toml for you. The derive feature is the one that lets you write one line above a struct and get all the parsing code written for you.
One line above the struct
Here is a small example first, apart from Chatterbox. Its struct has two new words on it: Serialize and Deserialize. They are traits, exactly like Replier in lesson 8.4: Serialize promises "I can be written out", Deserialize promises "I can be read back in". Writing the impl blocks by hand would mean a method that visits every field. Putting the trait names in #[derive(...)] (lesson 5.5) asks serde to write those impl blocks for you while the program compiles. You do not write any of it.
And serde_json::to_string is a generic function with a trait bound, the shape from lesson 8.4: it accepts any T as long as T: Serialize. Hand it something that never made the promise and you get the same E0277 you met there.
The field names become the JSON keys. The examples on this page call the fields role and content, the names a model's service expects (its API: the list of requests it accepts, and their exact shape). Chatterbox's own Message keeps author and text, so its JSON uses those names.
$ cargo run
{"role":"user","content":"hi"}
Message { role: "user", content: "hi" }Which text does this program print?
{"role":"assistant","content":"Hello!"}{"content":"Hello!","role":"assistant"}Message { role: "assistant", content: "Hello!" }
Reveal the answer
The program prints: {"role":"assistant","content":"Hello!"} serde writes the fields in the order the struct declares them, with the field names as quoted keys. It is JSON text, not the debug form of the struct.
Reading can fail
Writing a value as JSON practically always works: the struct is already shaped correctly. Reading is different, because the text came from outside. It might be missing a field, or not be JSON at all. That is why from_str returns a Result, the type from chapter 7. The example above used unwrap() to stay short. A real program matches on it, or uses ?, so bad text becomes an error message instead of a crash.
This is where Rust earns its keep. If the text is {"role":"assistant"} with no content, you find out right there, at the edge. You never carry a half-filled value through the rest of the program.
Fill in to_json so it returns the JSON text for a Message, and from_json so it returns Some(message) for good JSON and None for text that does not fit. .ok() on a Result gives an Option: Ok(v) becomes Some(v) and Err(_) becomes None.
Fill in to_json so it returns the JSON text for a Message, and from_json so it returns Some(message) for good JSON and None for text that does not fit. .ok() on a Result gives an Option: Ok(v) becomes Some(v) and Err(_) becomes None.
Hidden tests (4): not_json_is_none writes_expected_json round_trip_gives_same_message missing_field_is_none
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
Chatterbox saves JSON
Now the real program. Three files change in earnest, and the green lines show each one:
Cargo.tomlgains the two crates, exactly what the twocargo addcommands write.message.rsgains theuse serde::...line and#[derive(Serialize, Deserialize)]aboveMessage. That is the whole change to the type.store.rsgets shorter.to_linesandfrom_linesare gone: serde does their job now, for every field, with no splitting code.FILEbecomeschatterbox.json.savecallsserde_json::to_string_pretty, which writes the same JSON with line breaks and indents so a person can read the file.loadcallsserde_json::from_str(&text)?.
Two things about that load line. How does from_str know to build a list of messages? From the type load promises to return: Rust works it out, and serde builds a Vec<Message> because that is what is asked for. And the ? is doing a little extra. from_str fails with a serde_json error, but load promises an io::Error. serde_json ships a conversion from its error into an io::Error, and ? uses such a conversion by itself when the two types differ. That conversion is itself a trait, From, which serde_json implements for its error, and ? looks for exactly that. One more trait is quietly at work in save: a slice of Messages is Serialize because each Message is, so to_string_pretty(history) needs no extra code. main changes only its version number, to v0.9.
src/command.rsunchanged
src/replier.rsunchanged
Sam hello json /quit (run it again) Sam /quit
Chatterbox v0.9 (replies by: echo) What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. bot: you said: hello json bot: bye, Sam! messages so far: 1 saved 2 messages to chatterbox.json --- next run --- Chatterbox v0.9 (replies by: echo) What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. (I remember 2 messages from last time. /history shows them.) bot: bye, Sam! messages so far: 0 saved 2 messages to chatterbox.json
Download this version (zip)Unzip, then cargo run inside the folder.
Run it on your own machine and open the file it leaves behind. This is a real run of the program above, in an empty folder, followed by a look at the file and then by what happens when the file holds something that is not JSON.
$ printf 'Sam\nhello json\n/quit\n' | cargo run -q Chatterbox v0.9 (replies by: echo) What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. bot: you said: hello json bot: bye, Sam! messages so far: 1 saved 2 messages to chatterbox.json $ cat chatterbox.json [ { "author": "you", "text": "hello json" }, { "author": "bot", "text": "you said: hello json" } ] $ echo 'not json' > chatterbox.json $ printf 'Sam\n/quit\n' | cargo run -q Error: Custom { kind: InvalidData, error: Error("expected ident", line: 1, column: 2) }
The last run is the ? chain from chapter 7 doing its job: from_str failed, load passed the error up, main passed it out, and Rust printed it and stopped before the chat began, without overwriting the file. That message is written for programmers, not for people; a friendlier one would be a nice change to make yourself. One more honest note: the old chatterbox.log is not read any more, so a history saved before this lesson stays in that file.
If you have coded before
json.dumps(msg) and json.loads(text) do the same two jobs, and loads gives you a dict that may be missing keys, which you find out about later when you index it. Here the struct is the check: a reply that does not fit is rejected at the door.
What you have now
Chatterbox saves its whole history as JSON and reads it back, with serde writing the translation. That is also half of talking to a model: a request goes out as JSON and the reply comes back as JSON. Next lesson, the other half: a third Replier that sends the conversation to a real model as JSON and reads its JSON answer.
Say it out loud, then reveal
What are serializing and deserializing?Reveal
Why does <code>from_str</code> return a Result when <code>to_string</code> practically never fails?Reveal
What does <code>#[derive(Serialize, Deserialize)]</code> do?Reveal
That is lesson 9.1. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
What is JSON?
A plain-text format for data: curly braces for records, square brackets for lists, and quoted field names. Nearly every web API, including model APIs, uses it.
What is a crate in Rust?
A package of Rust code. You list the crates your project needs in Cargo.toml and cargo downloads and builds them.
Do I need serde to use JSON in Rust?
In practice yes. The standard library has no JSON support, and serde with serde_json is the common choice.
Sources serde · serde_json on docs.rs