typestar

Renaming fields in Rust

Rust names stay snake_case while the JSON keeps whatever the API expects.

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Step {
    step_index: u32,
    tour_slug: String,
    #[serde(rename = "tpm3")]
    target_tpm: u32,
    #[serde(alias = "name")]
    title: String,
}

fn main() -> Result<(), serde_json::Error> {
    let raw = r#"{"stepIndex":0,"tourSlug":"traits","tpm3":100,
                  "name":"Trait objects"}"#;
    let step: Step = serde_json::from_str(raw)?;
    println!("{:?}", step);
    println!("{}", serde_json::to_string(&step)?);
    Ok(())
}

How it works

  1. rename_all converts every field in one go.
  2. rename handles the one field that breaks the pattern.
  3. alias accepts an old key while writing the new one.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
506
Tokens
119
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 68 seconds.

Type this snippet

Step 1 of 3 in Field attributes, step 4 of 11 in Serde & JSON.

← Previous Next →