How to Parse JSON in Rust

Parse JSON in Rust using the serde_json crate and from_str function to convert strings into structs or Value types.

Use the serde_json crate to parse JSON strings into Rust structs or generic Value types. Add serde_json to your Cargo.toml dependencies, then call serde_json::from_str to deserialize the string.

use serde_json;

fn main() {
    let json = r#"{"name": "Alice", "age": 30}"#;
    let data: serde_json::Value = serde_json::from_str(json).unwrap();
    println!("{:#?}", data);
}

Add this to Cargo.toml:

[dependencies]
serde_json = "1"

For a specific struct, derive Deserialize from serde and parse directly:

use serde::Deserialize;
use serde_json;

#[derive(Deserialize)]
struct Person {
    name: String,
    age: u32,
}

fn main() {
    let json = r#"{"name": "Alice", "age": 30}"#;
    let person: Person = serde_json::from_str(json).unwrap();
    println!("{} is {} years old", person.name, person.age);
}

Add serde to Cargo.toml:

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"