rust 28 lines · 7 steps

Serializing config to JSON in Rust

Turn typed config structs into pretty JSON on disk with serde, skipping empty fields along the way.

Explained by highlit
1use std::fs::File;
2use std::io::{self, BufWriter};
3use std::path::Path;
4 
5use serde::Serialize;
6 
7#[derive(Serialize)]
8struct ServerConfig {
9 hostname: String,
10 port: u16,
11 #[serde(skip_serializing_if = "Vec::is_empty")]
12 allowed_origins: Vec<String>,
13 tls: TlsConfig,
14}
15 
16#[derive(Serialize)]
17struct TlsConfig {
18 enabled: bool,
19 #[serde(skip_serializing_if = "Option::is_none")]
20 cert_path: Option<String>,
21}
22 
23fn write_config(config: &ServerConfig, path: impl AsRef<Path>) -> io::Result<()> {
24 let file = File::create(path)?;
25 let mut writer = BufWriter::new(file);
26 serde_json::to_writer_pretty(&mut writer, config)?;
27 writer.flush()
28}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Deriving Serialize lets serde map struct fields to JSON without hand-written conversion code.
  2. 2skip_serializing_if keeps output clean by omitting empty or absent optional fields.
  3. 3Wrapping a File in BufWriter batches writes, but you must flush to guarantee the bytes hit disk.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Serializing config to JSON in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code