home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Read JSON Into A Rust Struct With Serde

January 2024
Code
//! ```cargo
//! [dependencies]
//! serde_json = "1.0.110"
//! serde = { version = "1.0.194", features = ["derive"] }
//! ```

#![allow(dead_code)]
use serde::Deserialize;
use serde_json;

#[derive(Debug, Deserialize)]
struct Site {
    title: String,
    pages: Vec<Page>
}

#[derive(Debug, Deserialize)]
struct Page {
    id: u32,
    content: String 
}

fn main() {
     let source = r#"{
        "title": "asdf",
        "pages": [
            { "id": 12, "content": "quick fox"},
            { "id": 37, "content": "slow dog"}
        ]
    }"#;
    let data: Site = serde_json::from_str(source).unwrap();
    println!("{:?}", data);
}
Results
Site { title: "asdf", pages: [Page { id: 12, content: "quick fox" }, Page { id: 37, content: "slow dog" }] }
═══ § ═══

Footnotes And References