Sub topic 5
Round-tripping JSON with serde_json
This chapter covers the working model of serde_json, the crate that turns Rust values into JSON text and back. It assumes you know Rust structs, traits, Result and ?, and have a Cargo project. It also assumes you know what JSON looks like, and that you have seen #[derive(Serialize, Deserialize)] from the previous chapter.
Setup
Add serde with its derive feature, plus serde_json:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"serde supplies the traits and derive macros. serde_json is the format crate. It implements serde's Serializer and Deserializer for JSON.
The round trip
A round trip converts a value to JSON and back. Two functions do most of the work:
serde_json::to_string(&value)returnsResult<String, serde_json::Error>.serde_json::from_str::<T>(&text)returnsResult<T, serde_json::Error>.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: u32,
name: String,
email: Option<String>,
}
fn main() -> Result<(), serde_json::Error> {
let user = User {
id: 1,
name: "Ada".to_string(),
email: None,
};
let json = serde_json::to_string(&user)?;
println!("{json}"); // {"id":1,"name":"Ada","email":null}
let back: User = serde_json::from_str(&json)?;
println!("{back:?}");
Ok(())
}Three details matter here:
to_stringborrows the value. You keep ownership ofuser.from_strneeds to know the target type. The annotationlet back: Userprovides it. You can also writefrom_str::<User>(&json).Nonebecomesnull, andnullbecomesNone.
Other entry points
to_string produces compact output. Several siblings cover other needs:
| Function | Purpose |
|---|---|
| `to_string_pretty` | Indented output for humans |
| `to_vec` | JSON as `Vec<u8>` |
| `to_writer` | Writes into any `std::io::Write`, such as a file |
| `from_slice` | Parses from `&[u8]` |
| `from_reader` | Parses from any `std::io::Read` |
Prefer to_writer for large values or files. It avoids building the whole String in memory first.
What the deserializer checks
Parsing checks two things at once: the text must be valid JSON, and its shape must match the target type. These inputs fail for User:
{"id":1,"name":"Ada"is invalid JSON because the closing brace is missing.{"id":"one","name":"Ada","email":null}has a string whereu32is expected.{"id":1,"email":null}has noname.
By default, unknown keys are ignored. Missing Option<T> fields become None. Any other missing field is an error unless you give it a default. The next chapters cover how to change these rules with attributes.
Common mistakes
- Forgetting the
derivefeature. The error says theSerializeorDeserializederive macro cannot be found. - Omitting the target type on
from_str. The compiler reports that it cannot infer the type. - Passing the value without a reference to
to_string. The function takes&T, so write&user. - Using
unwrap()on parse results for untrusted input. Return the error with?or handle it.
Exercise
You call serde_json::from_str(r#"{"id":1,"name":"Ada"}"#) and bind the result to let u: User, using the User struct above. Does it succeed, and what is u.email?
Show answer
It succeeds. The email key is missing, and a missing Option<String> field deserializes to None. Fields of any other type would cause a "missing field" error.
Exercise
Which function would you use to write a User straight to an open File without building a String first?
Show answer
serde_json::to_writer(&mut file, &user), or serde_json::to_writer_pretty for indented output.