Skip to main content

How to Rename a Field in JSON with serde rename in Rust

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

#[serde(rename = "type")] above a struct field makes serde write that field to JSON as type, and read it back from type, while your Rust code keeps calling it kind. That's how a JSON key that can't be a Rust field name, such as the keyword type, maps to a field.

Syntax​

Syntax
#[derive(Serialize, Deserialize)]
struct <Name> {
#[serde(rename = "<name in JSON>")]
<field>: <type>,
}
PartWhat it does
#[derive(Serialize, Deserialize)]Lets serde turn the struct into JSON and back.
#[serde(rename = "<name in JSON>")]Gives the field below it this name in JSON, both when writing and when reading.
<field>The field's name in your Rust code.

The serde documentation, Field attributes, describes #[serde(rename = "name")]: "Serialize and deserialize this field with the given name instead of its Rust name."

The Example​

The example's photo has a title and a kind, which its JSON calls type. type is a keyword in Rust, so the field is named kind, and rename maps it to type. The code writes one photo as JSON and reads another one from JSON. Then a changed version leaves out the attribute.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project​

Terminal
cargo new demo
cd demo
cargo add serde --features derive
cargo add serde_json

cargo new demo creates the project. cargo add serde --features derive adds serde, version 1.0.229 here, with the derive feature, which writes the code that turns a struct into JSON and back. cargo add serde_json adds serde_json, version 1.0.154 here, which reads and writes the JSON text.

Step 2: Write the Code​

Replace the contents of src/main.rs:

src/main.rs, with a Photo struct whose kind field carries serde rename type, a main that writes a photo titled Sunset of the kind landscape as JSON, and reads a photo titled Harbour with the type portrait from JSON.

src/main.rs
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Photo {
title: String,
#[serde(rename = "type")]
kind: String,
}

fn main() {
let photo = Photo {
title: String::from("Sunset"),
kind: String::from("landscape"),
};
let json = serde_json::to_string(&photo).expect("the photo turns into JSON");
println!("{json}");

let read: Photo = serde_json::from_str(r#"{"title":"Harbour","type":"portrait"}"#)
.expect("the JSON has a title and a type");
println!("{read:?}");
}
  • #[serde(rename = "type")] names the kind field type in JSON.
  • serde_json::to_string(&photo) writes the photo as JSON text.
  • serde_json::from_str(...) reads a Photo from JSON text. r#"..."# is a raw string, so the double quotes inside it need no backslashes.
  • .expect(...) stops the program with that message if a step fails.

Step 3: Run It​

Terminal
cargo run -q
Output
{"title":"Sunset","type":"landscape"}
Photo { title: "Harbour", kind: "portrait" }

The command is the same in zsh, bash and PowerShell.

Step 4: Leave Out the Attribute​

Replace src/main.rs with the same code without #[serde(rename = "type")]:

src/main.rs
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Photo {
title: String,
kind: String,
}

fn main() {
let photo = Photo {
title: String::from("Sunset"),
kind: String::from("landscape"),
};
let json = serde_json::to_string(&photo).expect("the photo turns into JSON");
println!("{json}");

let read: Photo = serde_json::from_str(r#"{"title":"Harbour","type":"portrait"}"#)
.expect("the JSON has a title and a type");
println!("{read:?}");
}
Terminal
cargo run -q
Output
{"title":"Sunset","kind":"landscape"}

thread 'main' (1521065) panicked at src/main.rs:18:10:
the JSON has a title and a type: Error("missing field `kind`", line: 1, column: 37)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

A zsh terminal where cargo run -q prints JSON with title Sunset and type landscape and then the Photo read back with kind portrait; for the changed file, it prints JSON with kind instead of type and panics with missing field kind.

What Happened​

  • {"title":"Sunset","type":"landscape"}: serde wrote the kind field under the name type.
  • Photo { title: "Harbour", kind: "portrait" }: reading went the other way, and the JSON's type filled kind.
  • Without the attribute, the field kept its Rust name. The JSON it wrote had kind, and reading JSON with type failed with missing field `kind` . serde skipped the type key, because no field had that name: in a separate check, a struct with only a title read the same JSON without an error.

Common Mistakes​

MistakeWhat happensDo this instead
Naming the field typeerror: expected identifier, found keyword `type`, with the help "escape type to use it as an identifier"Give it another name with rename, as here, or write r#type, which serde wrote as type
#[rename = "type"], without serde(...)error: cannot find attribute `rename` in this scopeWrite #[serde(rename = "type")]
A misspelled attribute, such as renmaeerror: unknown serde field attribute `renmae`Fix the spelling

Troubleshooting​

SymptomLikely causeFix
Error("missing field `kind`", line: 1, column: 37)The JSON uses another name for the fieldAdd #[serde(rename = "...")] with the JSON's name
JSON keys in camelCase, such as storageGb, for fields in snake_case, such as storage_gbEvery field would need its own renamePut rename_all on the struct: with #[serde(rename_all = "camelCase")], storage_gb was written as storageGb

FAQ​

Can the name in JSON be a URL?​

Yes. #[serde(rename = "https://photos.example.org/quota")] on a field named quota wrote {"https://photos.example.org/quota":10}.

Can a field have one name for writing and another for reading?​

Yes: #[serde(rename(serialize = "Title", deserialize = "title"))] wrote {"Title":"Sunset"} and read {"title":"Harbour"}.

How do I accept two names when reading?​

Add alias, which the serde documentation describes as "Deserialize this field from the given name or from its Rust name." With #[serde(rename = "type", alias = "kind")], both {"type":"portrait"} and {"kind":"portrait"} were read into kind.

Conclusion​

#[serde(rename = "...")] gives a struct field its own name in JSON, for writing and for reading, while the Rust code keeps a name that suits Rust. Use it for keys that are keywords, URLs or names in another style, and rename_all when every field follows the same style.

Additional Resources​