Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Read JSON Into A Rust Struct With Serde

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" }] }

References