rust
28 lines · 8 steps
Trimming JSON output with serde attributes
How serde attributes control which struct fields appear in serialized JSON.
Explained by
highlit
1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Serialize, Deserialize)]
4pub struct UserProfile {
5 pub id: u64,
6 pub username: String,
7
8 #[serde(skip_serializing_if = "Option::is_none")]
9 pub display_name: Option<String>,
10
11 #[serde(skip_serializing_if = "Option::is_none")]
12 pub bio: Option<String>,
13
14 #[serde(skip_serializing_if = "Option::is_none", rename = "avatar")]
15 pub avatar_url: Option<String>,
16
17 #[serde(skip_serializing_if = "Vec::is_empty", default)]
18 pub roles: Vec<String>,
19
20 #[serde(skip_serializing_if = "Option::is_none")]
21 pub last_login: Option<chrono::DateTime<chrono::Utc>>,
22}
23
24impl UserProfile {
25 pub fn to_json(&self) -> serde_json::Result<String> {
26 serde_json::to_string_pretty(self)
27 }
28}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1serde attributes let you shape the wire format without changing your Rust field names or types.
- 2Skipping empty optionals and collections keeps JSON output compact and free of null noise.
- 3Pairing skip_serializing_if with default makes a type both clean to emit and forgiving to parse.
Related explainers
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
rust
use axum::{ body::Body, extract::Path, http::{header, HeaderMap, HeaderValue, StatusCode},
HTTP range requests for video streaming in Axum
http-range-requests
streaming
async-io
Advanced
8 steps
ruby
require "base64" require "json" module Attachment
Packing binary attachments into JSON
serialization
base64
json
Intermediate
8 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/trimming-json-output-with-serde-attributes-explained-rust-f4ac/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.