home ~ projects ~ socials

Read a JSON String into a Rust Struct with serde

Bring It In

This is how I'm pulling a string of JSON into a Rust struct:

---
[dependencies]
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
---

#![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();
    dbg!(data);
}
Output:
[/Users/alan/.cargo/target/4b/0baba35be9214e/_active_nvim_run:32:5] data = Site {
    title: "asdf",
    pages: [
        Page {
            id: 12,
            content: "quick fox",
        },
        Page {
            id: 37,
            content: "slow dog",
        },
    ],
}

Notes

  • The #![allow(dead_code)] prevents a warning that shows up because this example doesn't really use the Site and Page struct. It wouldn't be necessary in practical code.

Super handy.

-a

-- end of line --

References