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
python
from datetime import datetime from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel, ConfigDict, EmailStr from sqlalchemy.orm import Session
Building a users router in FastAPI
routing
serialization
dependency-injection
Intermediate
7 steps
typescript
type Event = Record<string, unknown>; interface BatcherOptions { endpoint: string;
Batching analytics events in TypeScript
batching
buffering
async
Intermediate
8 steps
python
import json from dataclasses import dataclass, field, asdict from datetime import datetime from typing import Any
JSON round-tripping with Python dataclasses
dataclasses
serialization
json
Intermediate
6 steps
javascript
const logger = require('./logger'); class AppError extends Error { constructor(message, statusCode = 500, details = null) {
Centralized error handling in Express
error-handling
middleware
custom-errors
Intermediate
8 steps
php
<?php namespace App\Services;
Resilient HTTP retries with Laravel's client
http-client
retry-logic
error-handling
Intermediate
7 steps
ruby
class ArticleSerializer < ActiveModel::Serializer attributes :id, :title, :slug, :excerpt, :reading_time, :published_at, :url belongs_to :author, serializer: UserSerializer
Shaping API output with ActiveModel::Serializer in Rails
serialization
json api
computed attributes
Intermediate
9 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.