JSON in Rust — serde_json Guide
The de-facto standard for JSON in Rust is serde_json, built on the serde serialization framework. Add serde = { version = "1", features = ["derive"] } and serde_json = "1" to your Cargo.toml.
Deserialize JSON into a struct
Derive Deserialize on your struct and use serde_json::from_str().
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct User {
id: u32,
name: String,
email: String,
}
fn main() {
let json = r#"{"id":1,"name":"Alice","email":"alice@example.com"}"#;
let user: User = serde_json::from_str(json).unwrap();
println!("{}", user.name); // Alice
}Serialize a struct to JSON
Derive Serialize and use serde_json::to_string() or to_string_pretty().
use serde::Serialize;
#[derive(Serialize)]
struct User { id: u32, name: String }
let user = User { id: 1, name: "Alice".into() };
let json = serde_json::to_string(&user).unwrap();
// {"id":1,"name":"Alice"}
let pretty = serde_json::to_string_pretty(&user).unwrap();Dynamic JSON with serde_json::Value
Use serde_json::Value for JSON with an unknown shape. Access fields with square-bracket indexing.
use serde_json::Value;
let json = r#"{"name":"Alice","scores":[95,87]}"#;
let v: Value = serde_json::from_str(json).unwrap();
println!("{}", v["name"]); // "Alice"
println!("{}", v["scores"][0]); // 95Related Tools
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →