---
title: "Deserialize a YAML value into a Rust struct"
url: https://recursiveai.org/oneyaml/rust/cookbook/convert-yaml-value-to-struct/
description: "Deserialize a YAML Value into a Rust struct with Serde. Select a nested section and convert it with from_value without modeling the whole document."
version: "1.2.0"
---

# 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.

[crates.io](https://crates.io/crates/oneyaml) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-rust) · [Docs](https://recursiveai.org/oneyaml/rust/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/rust/cookbook/convert-yaml-value-to-struct/convert-yaml-value-to-struct.zip)

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

```shell
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](https://recursiveai.org/oneyaml/rust/cookbook/convert-yaml-value-to-struct/convert-yaml-value-to-struct.zip), 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.

## Related recipes

- [Read YAML in Rust without a struct](https://recursiveai.org/oneyaml/rust/cookbook/read-yaml-without-a-schema/)
- [Parse YAML into Rust structs](https://recursiveai.org/oneyaml/rust/cookbook/parse-yaml-into-structs/)
- [Convert a Rust struct to a YAML value](https://recursiveai.org/oneyaml/rust/cookbook/serialize-struct-to-yaml-value/)

## The short answer

Use [`from_value`](https://docs.rs/oneyaml/1.2.0/oneyaml/fn.from_value.html) 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](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/de/value.rs#L82-L93).

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`](https://docs.rs/oneyaml/1.2.0/oneyaml/struct.NodeRef.html#method.deserialize). If your entire input already has a known schema, deserialize it directly into the root struct instead of building a dynamic tree first.
