How to Parse JSON in Rust

← All guides

Rust uses the serde + serde_json crates. Derive Serialize/Deserialize on your structs, then use from_str and to_string_pretty.

Deserialize into a struct

Derive Deserialize and call serde_json::from_str with a target type.

rust
use serde::Deserialize;

#[derive(Deserialize)]
struct User {
    name: String,
    roles: Vec<String>,
}

let u: User = serde_json::from_str(text)?;
println!("{} {:?}", u.name, u.roles);

Work with untyped JSON

serde_json::Value handles arbitrary JSON without a struct.

rust
use serde_json::Value;

let v: Value = serde_json::from_str(text)?;
println!("{}", v["name"]);

Serialize and pretty-print

to_string produces compact JSON; to_string_pretty indents it.

rust
let json = serde_json::to_string(&u)?;
let pretty = serde_json::to_string_pretty(&u)?;

Frequently Asked Questions

Add serde with the derive feature and serde_json to Cargo.toml: serde = { version = "1", features = ["derive"] } and serde_json = "1".

Use the JSON to Rust tool to generate serde-annotated structs from a sample JSON document.

Use Option<T> for fields that may be missing or null; serde will deserialize them to None.

Related Tools