Parse a json with arrays with serde

I would like to parse a json with an array inside:

#[derive(Debug, Deserialize)]
pub struct Device {
    pub path: String,
    pub start_sector: Option<u64>,
    pub end_sector: Option<u64>,
}

#[derive(Debug, Deserialize)]
pub struct Config {
    pub hostname: String,
    pub devices: [Option<Device>],
}

Anyhow I cannot manage to deserialize an object with an array inside, as I get: error: cannot deserialize a dynamically sized struct. You can find my attempts here.

How can I parse variable length arrays in serde?

Arrays are always of fixed length in Rust. What you want is a Vec.
Hence, you must define Config as:

#[derive(Debug, Deserialize)]
pub struct Config {
    pub hostname: String,
    pub devices: Vec<Option<Device>>,
}
1 Like

Thanks. Do you think the Option is needed? Since the vec is variable length I could drop it right?

That depends on the structure of the data you're dealing. If it is like: [{...}, {....}, "null", {...} ...], then you need the Option. Otherwise, you don't.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.