Recursive AI

Deserialize one YAML section into a Rust struct

oneyaml is a free, open-source YAML library for Rust from Recursive AI. MIT or Apache-2.0, no unsafe code.

Call deserialize() on the section’s node.

Terminal
cargo add oneyaml serde -F serde/derive
RUST
use oneyaml::Document;
#[derive(serde::Deserialize)]
struct Server { port: u16 }
fn main() -> Result<(), oneyaml::Error> {
    let yaml =
        "service: {server: {port: 8080}}";
    let doc = Document::parse(yaml)?;
    let node = doc.get_path("service.server")
        .expect("service.server exists");
    let server: Server = node.deserialize()?;
    println!("Port: {}", server.port);
    Ok(())
}

The example is the full program below: unzip it and cargo run. To run only the code above, paste it into src/main.rs of a new cargo new example project and cargo run.

Only the server port is printed:

Text
Port: 8080

Full program

The download uses Rust 1.85 or later and reads this config.yaml:

YAML
service:
  server:
    port: 8080
  logging: verbose
RUST
use oneyaml::Document;
use serde::Deserialize;
 
#[derive(Deserialize)]
struct Server {
    port: u16,
}
 
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let yaml = std::fs::read_to_string("config.yaml")?;
    let doc = Document::parse(&yaml)?;
    let node = doc
        .get_path("service.server")
        .ok_or("missing service.server")?;
    let server: Server = node.deserialize()?;
    println!("Port: {}", server.port);
    Ok(())
}

cargo run prints:

Text
Port: 8080

If the section is missing, the lookup reports missing service.server; if the section exists but port can’t be read as a u16, deserialization returns an error.

Variations

Make the section optional. Replace the lookup, deserialization, and print lines. A missing section prints No server configured; if the section exists but doesn’t fit Server, the deserialization error still reaches the caller.

RUST
if let Some(node) = doc.get_path("service.server") {
    let server: Server = node.deserialize()?;
    println!("Port: {}", server.port);
} else {
    println!("No server configured");
}

The short answer

Parse the file as a Document, select the NodeRef for the section you want, and call node.deserialize() with the desired Rust type. In oneyaml-rust, Server only describes the mapping under service.server. You don’t need wrapper structs for the root or service, and you don’t need to convert the selected mapping back to YAML text.

How can I deserialize just an inner YAML block in Rust?

Give the struct only the fields that live inside the selected mapping. Here Server has port, not server or service. Those two outer names are how you reach the mapping, while logging is a sibling that isn’t deserialized into Server. For a list of server mappings, select the list and deserialize into Vec<Server>, or select one item by putting its zero-based index in the path and deserialize that item into Server.

If you already have a dynamic Value tree, from_value is another way to read a selected section. With a Document, NodeRef::deserialize reads the selected node directly and keeps the original document available for later reads or edits. It can also follow an alias inside the selected section to an anchor elsewhere in the document; the selected node is not an isolated YAML string.

How do you read a YAML file into a Rust struct?

When the whole file has a known shape and you need all of it, deserialize into a root struct. When you only need one section, read the text as the download does, parse the document, and select the section before checking its fields. Parsing still reads the file: selecting a node doesn’t bypass malformed YAML elsewhere in a normal Document::parse.

Keep lookup errors separate from type errors. In the example a missing service.server produces a message about the missing section before Serde runs. If port is present but not a u16, the deserialization error’s path is relative to the selected node, but its source span still points into the original file. That lets you show the reader the location without reconstructing the section from the error path.

All oneyaml Rust recipes