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 serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 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
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
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/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.