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

Walkthrough

Space play step click any line
Three takeaways
  1. 1serde attributes let you shape the wire format without changing your Rust field names or types.
  2. 2Skipping empty optionals and collections keeps JSON output compact and free of null noise.
  3. 3Pairing skip_serializing_if with default makes a type both clean to emit and forgiving to parse.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Trimming JSON output with serde attributes — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code