Recursive AI

Deserialize a YAML value 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.

Use from_value on one YAML section, without defining a struct for the whole file.

Terminal
cargo add oneyaml
cargo add serde -F derive
RUST
use oneyaml::Value;
use serde::Deserialize;
 
#[derive(Deserialize)]
struct Server {
    port: u16,
}
 
fn main() -> Result<(), oneyaml::Error> {
    let doc: Value = oneyaml::from_str(
        "server: {port: 8080}",
    )?;
    let section = doc["server"].clone();
    let server: Server =
        oneyaml::from_value(section)?;
    println!("Port: {}", server.port);
    Ok(())
}

Prints:

Text
Port: 8080

A missing port or a value that doesn’t fit in a u16 returns a deserialization error.

Unzip the example, then cargo run.

Requires Rust 1.85 or later.

Variations

Take the section without cloning it

Replace the parse, selection, and conversion lines in main with these if you own the document and no longer need its server entry:

RUST
let mut doc: Value = oneyaml::from_str(
    "server: {port: 8080}",
)?;
let Some(section) = doc.as_mapping_mut()
    .and_then(|map| {
        map.remove(&Value::from("server"))
    })
else {
    eprintln!("Expected a server section");
    return Ok(());
};
let server: Server =
    oneyaml::from_value(section)?;

The successful run still prints Port: 8080; the missing-section branch runs before Serde sees the data.

The short answer

Use from_value to deserialize an existing YAML Value. Give the result a type that implements Deserialize. The function takes ownership of the value, so clone a selected section if you still need the original tree, or remove it from the mapping to pass it by value. There’s no need to write the section back to YAML and parse that string.

How do I deserialize only a nested YAML block in Rust?

Parse the root into Value and navigate to the block you want. In the example, the block is the mapping under server, so the Server struct has a port field but no server field. The same idea works for a mapping inside a list: pick the list item first, then convert that item to the corresponding type.

Indexing with doc["server"] is fine when the key should always be there. If a missing key needs its own error, check for it first, as in the variation. In particular, indexing a missing key yields Value::Null, so an indexed lookup alone can’t tell you whether a key is absent or was written with an explicit null.

Why does deserializing a YAML value into a struct fail?

Match the Rust field type to the data already in the tree. An unquoted port: 8080 resolves to a number; port: "8080" is a string. A String field won’t accept the already resolved number through from_value. Direct deserialization from text is different: from_str can read the original spelling of a plain scalar into a string.

The error can identify the field within the selected value, but that value no longer has its original line or column. If you need to point readers back to the YAML file, keep the source and deserialize the corresponding document node using NodeRef::deserialize. If your entire input already has a known schema, deserialize it directly into the root struct instead of building a dynamic tree first.

All oneyaml Rust recipes