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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Deriving Serialize lets serde map struct fields to JSON without hand-written conversion code.
- 2skip_serializing_if keeps output clean by omitting empty or absent optional fields.
- 3Wrapping a File in BufWriter batches writes, but you must flush to guarantee the bytes hit disk.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/serializing-config-to-json-in-rust-explained-rust-1439/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.