How to Parse JSON in Rust
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)?;