Sub topic 5
Round-tripping JSON with serde_json
A round trip turns a Rust value into JSON text and then back into an equal Rust value. This chapter covers the serde_json functions that do this, the input and output types they accept, and the cases where the result differs from what you expected. It assumes you can read basic Rust, use ? with Result, and already derived Serialize and Deserialize in the previous chapter.
Setup
Add serde with the derive feature, and serde_json:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"serde_json is the format crate. It implements serde's Serializer and Deserializer traits for JSON. Your types stay format-neutral, and the crate handles the JSON syntax.
A complete round trip
The example below uses nested structs, a Vec, a map, and an Option. It uses BTreeMap rather than HashMap so the key order in the output is stable.
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Item {
sku: String,
qty: u32,
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Order {
id: u64,
items: Vec<Item>,
tags: BTreeMap<String, String>,
note: Option<String>,
}
fn main() -> Result<(), serde_json::Error> {
let mut tags = BTreeMap::new();
tags.insert("gift".to_string(), "yes".to_string());
let order = Order {
id: 7,
items: vec![
Item { sku: "A-1".to_string(), qty: 2 },
Item { sku: "B-9".to_string(), qty: 1 },
],
tags,
note: None,
};
let json = serde_json::to_string(&order)?;
println!("{json}");
// {"id":7,"items":[{"sku":"A-1","qty":2},{"sku":"B-9","qty":1}],"tags":{"gift":"yes"},"note":null}
println!("{}", serde_json::to_string_pretty(&order)?);
let back: Order = serde_json::from_str(&json)?;
assert_eq!(order, back);
Ok(())
}Points to notice:
to_stringtakes a reference and returns compact JSON.to_string_prettyreturns the same data with two-space indentation.from_stris generic over its return type. The annotationlet back: Ordertells it what to build. You can also writeserde_json::from_str::<Order>(&json).PartialEqon the types lets you assert that the round trip preserved the value. This is a cheap and useful test for any type you serialize.- The error type is
serde_json::Error, somaincan return it directly.
Mapping Rust types to JSON
Most mappings are what you would guess. A few are not.
| Rust type | JSON form |
|---|---|
| `bool`, integers, floats | `true`/`false`, number |
| `String`, `&str`, `char` | string |
| `Option<T>` | `null` or the inner value |
| `Vec<T>`, arrays, slices | array |
| Tuples and tuple structs | array |
| Newtype struct `struct Id(u64)` | the inner value, with no wrapper |
| Unit `()` and unit structs | `null` |
| Structs, `HashMap`, `BTreeMap` | object |
Some details that cause surprises:
- Non-finite floats.
f64::NANand infinities serialize asnull, because JSON has no representation for them. Deserializing thatnullback into anf64fails, so the round trip is not lossless. - Map keys. JSON object keys are strings.
serde_jsonaccepts string keys and integer keys, which it writes as strings, such as{"1":"a"}. Keys that cannot become strings, such as aVec<u8>or a struct, fail at serialization time with an error. - Map ordering. A
HashMapserializes in iteration order, which varies between runs. UseBTreeMapwhen you compare output text or write golden files. - Integer width. Reading
300into au8is an error rather than a silent wrap. Reading-1into au32is also an error.
Choosing input and output types
from_str and to_string are the convenient forms. The same operations exist for bytes and for I/O streams.
| Direction | Function | Source or sink |
|---|---|---|
| Serialize | `to_string`, `to_string_pretty` | `String` |
| Serialize | `to_vec`, `to_vec_pretty` | `Vec<u8>` |
| Serialize | `to_writer`, `to_writer_pretty` | anything implementing `std::io::Write` |
| Deserialize | `from_str` | `&str` |
| Deserialize | `from_slice` | `&[u8]` |
| Deserialize | `from_reader` | anything implementing `std::io::Read` |
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{BufReader, BufWriter};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Settings {
theme: String,
font_size: u8,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let settings = Settings { theme: "dark".to_string(), font_size: 14 };
// Bytes in memory.
let bytes = serde_json::to_vec(&settings)?;
let from_bytes: Settings = serde_json::from_slice(&bytes)?;
assert_eq!(settings, from_bytes);
// A file, with buffering on both sides.
let path = std::env::temp_dir().join("serde_roundtrip_settings.json");
let writer = BufWriter::new(File::create(&path)?);
serde_json::to_writer_pretty(writer, &settings)?;
let reader = BufReader::new(File::open(&path)?);
let from_file: Settings = serde_json::from_reader(reader)?;
assert_eq!(settings, from_file);
std::fs::remove_file(&path)?;
println!("round trips ok");
Ok(())
}Two practical rules:
- Wrap files and sockets in
BufReaderandBufWriter.serde_jsonreads and writes in very small pieces, and without buffering each piece becomes a system call. - If the whole document is already in memory,
from_strorfrom_sliceis usually faster thanfrom_reader. Slice and string input can also support borrowed deserialization, which a later chapter covers.
The generic error type Box<dyn std::error::Error> in this example is needed because File operations return std::io::Error, while serde returns serde_json::Error. The ? operator converts both into the box.
What deserialization accepts
Deserializing is stricter about types than about structure. The defaults are:
- Unknown keys are ignored.
{"id":1,"extra":true}reads into a struct with onlyid. Container attributes can change this, and a later chapter covers them. - Key order does not matter. Fields can appear in any order.
- Missing
Optionfields becomeNone. The derive treatsOption<T>fields as optional when the key is absent. A missing field of any other type is an error unless it has a default. - Numbers are not coerced. The JSON string
"7"does not become the integer7, and the float1.5does not become an integer. - The whole input must be one value. Anything but whitespace after the value is an error.
The following program shows each failure and what serde_json::Error tells you about it:
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Item {
id: u64,
label: Option<String>,
}
fn main() {
let inputs = [
r#"{"id":1}"#, // ok: label is None
r#"{"label":"x"}"#, // missing field
r#"{"id":"1"}"#, // wrong type
r#"{"id":1,"label":"x"} 2"#, // trailing characters
r#"{"id":1,"#, // truncated input
];
for input in inputs {
match serde_json::from_str::<Item>(input) {
Ok(item) => println!("ok: {item:?}"),
Err(e) => println!(
"{:?} at line {}, column {}: {e}",
e.classify(),
e.line(),
e.column()
),
}
}
}classify() returns a Category: Io, Syntax, Data, or Eof. Data means the JSON was well formed but did not fit the type, which covers the missing field and wrong type cases. Eof means the input ended early. Syntax means malformed JSON. The error Display output includes the line and column. The next chapters on error handling cover how to report these to users.
Reading several values from one stream
from_str rejects text containing more than one top-level value. Some formats, such as newline-delimited JSON, put many values in one stream. For these, build a Deserializer and iterate over it:
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Item {
sku: String,
qty: u32,
}
fn main() -> Result<(), serde_json::Error> {
let text = r#"{"sku":"A","qty":1} {"sku":"B","qty":2}"#;
let stream = serde_json::Deserializer::from_str(text).into_iter::<Item>();
for item in stream {
println!("{:?}", item?);
}
Ok(())
}Each iteration yields a Result<Item, serde_json::Error>, so one bad record does not stop you from deciding how to proceed.
Common mistakes
- Using
unwrapon parse results. Input is untrusted. Propagate the error or map it to your own error type. - Expecting
HashMapoutput to be stable. Sort or useBTreeMapwhen order matters. - Reading a large file with
read_to_stringand thenfrom_strwhenfrom_readerwould do. The second approach avoids holding both the text and the parsed value, thoughfrom_strremains faster for small inputs. Measure if it matters. - Assuming
nulland "missing" are the same everywhere. ForOptionfields on deserialization they are. On serialization,Noneis written asnullunless you addskip_serializing_if, as the attributes chapter shows. - Assuming
f64round trips exactly. Ordinary finite values do. Non-finite values do not, as described above.
Exercise
A struct has the fields id: u32 and nickname: Option<String>. What does serde_json::from_str do with the input {"id": 5}, and what does it do with {"nickname": "ada"}? Which category does Error::classify report for the second case?
Show answer
The first input succeeds with id = 5 and nickname = None, because the derive treats a missing Option field as None. The second input fails because the required field id is missing. The JSON is well formed but does not fit the type, so classify() returns Category::Data.
Exercise
You need to read a log file that contains one JSON object per line, and you want to keep going if a single line is malformed. Which approach fits, and why is serde_json::from_str on the whole file a poor choice?
Show answer
Read the file line by line (for example with BufRead::lines) and call from_str on each line, handling each Result separately. Alternatively, use Deserializer::from_str(...).into_iter::<T>(), which yields one Result per value. Calling from_str on the whole file fails with a trailing characters error as soon as a second value appears, because it expects exactly one top-level value.