expression

Omit optional fields on output

Skip an output field when its predicate returns true. This changes the wire representation but not the in-memory value. Serde and serde_json are external crates; use the staged Cargo manifest. Expected stdout (not executed): {"id":2} Common mistake: Treating omission as a substitute for authorization or secret redaction.

Formal Syntax & Structure

rust syntaxrust
#[serde(skip_serializing_if = "Option::is_none")]

Working Example

Example Snippetrust
fn main() {    #[derive(serde::Serialize)]    struct Note { id: u8, #[serde(skip_serializing_if = "Option::is_none")] text: Option<String> }    println!("{}", serde_json::to_string(&Note { id: 2, text: None }).unwrap());}
Rust Reference