How to Format JSON in Rust
Feb 06, 2026 3 min read
The standard way to work with JSON in Rust is to use the serde and serde_json crates. By using serde_json::to_string_pretty, you can effortlessly serialize your structs or maps into an indented string.
Example Code
Rust
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct User {
name: String,
age: u8,
city: String,
skills: Vec<String>,
}
fn main() {
let user = User {
name: String::from("John"),
age: 30,
city: String::from("New York"),
skills: vec![String::from("Rust"), String::from("WASM")],
};
match serde_json::to_string_pretty(&user) {
Ok(formatted_json) => println!("{}", formatted_json),
Err(e) => println!("Error formatting JSON: {}", e),
}
} Common Use Cases
- Creating CLI outputs for systems written in Rust
- Formatting serialized API models locally
- Writing structured readable debug files to disk
💡 Pro Tips for Rust
- Make sure you enable the
derivefeature on theserdecrate inside yourCargo.toml. - If you are writing straight to a file or stdout stream you should use
serde_json::to_writer_prettyinstead to save memory allocation mapping to a huge string.
Professional JSON Tools
Developing in Rust requires precision. Use our validator to ensure your sample JSON files are strictly compliant before running <code>serde</code>.