---
title: "Keep YAML mapping keys in insertion order in Rust"
url: https://recursiveai.org/oneyaml/rust/cookbook/keep-yaml-mapping-as-insertion-order/
description: "Deserialize YAML into an insertion-ordered Rust Mapping and iterate keys in file order instead of sorting them or relying on hash map iteration."
version: "1.2.0"
---

# Keep YAML mapping keys in insertion order in Rust

**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/keep-yaml-mapping-as-insertion-order/keep-yaml-mapping-as-insertion-order.zip)

Read into `Mapping` to list YAML keys in the order they appear in the file.

```shell
cargo add oneyaml
```

```rust
fn main() -> Result<(), oneyaml::Error> {
    let yaml = "zebra: 1\nant: 2\nmoth: 3";
    let map: oneyaml::Mapping =
        oneyaml::from_str(yaml)?;
    for key in map.keys() {
        if let Some(name) = key.as_str() {
            println!("{name}");
        }
    }
    Ok(())
}
```

Paste the code above into src/main.rs of a new `cargo new example` project and `cargo run`, or unzip [the example](https://recursiveai.org/oneyaml/rust/cookbook/keep-yaml-mapping-as-insertion-order/keep-yaml-mapping-as-insertion-order.zip) and `cargo run`.

Requires Rust 1.85 or later. The example prints:

```text
zebra
ant
moth
```

`from_str::<Mapping>` returns an error if the document root isn’t a mapping. The loop prints only string keys.

## Variations

### Read integer keys without sorting them

Replace the input and loop in `main` with the code below. It prints `10` and then `2`, one per line.

```rust
let yaml = "10: ten\n2: two";
let map: oneyaml::Mapping =
    oneyaml::from_str(yaml)?;
for key in map.keys() {
    if let Some(number) = key.as_i64() {
        println!("{number}");
    }
}
```

### Keep key order in a struct field

`oneyaml::Mapping` also works as a field in a struct that derives `Deserialize`. Run `cargo add serde --features derive`, then replace `src/main.rs` with this program:

```rust
#[derive(serde::Deserialize)]
struct Config {
    animals: oneyaml::Mapping,
}

fn main() -> Result<(), oneyaml::Error> {
    let yaml = "animals: {zebra: 1, ant: 2}";
    let config: Config = oneyaml::from_str(yaml)?;
    for key in config.animals.keys() {
        if let Some(name) = key.as_str() {
            println!("{name}");
        }
    }
    Ok(())
}
```

It prints:

```text
zebra
ant
```

## Related recipes

- [Read YAML without a schema](https://recursiveai.org/oneyaml/rust/cookbook/read-yaml-without-a-schema/)
- [Reorder YAML keys and keep comments](https://recursiveai.org/oneyaml/rust/cookbook/reorder-yaml-keys-keep-comments/)

## The short answer

Deserialize into `oneyaml::Mapping` with `oneyaml::from_str`. Its `keys()` iterator follows insertion order; `iter()` gives you the keys and values in that same order. Here `zebra` comes first because it’s first in the input, not because it sorts ahead of `ant`. Use this when you want to list settings in the order someone wrote them without making that order part of your configuration’s meaning.

## Does YAML preserve key order?

The [YAML specification](https://yaml.org/spec/1.2.2/#3221-mapping-key-order) treats mapping keys as unordered. That doesn’t stop a parser from remembering their order in the file. The [pinned `Mapping` documentation](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/value/mapping.rs#L29-L41) separates the two: iteration follows insertion order, but equality and hashing don’t. Two mappings with the same entries compare equal even if one lists `ant` first and the other lists `zebra` first.

Choose a sequence instead if order changes what the data means. For example, the order in which build steps execute should come from a YAML list, not from the position of named keys in a mapping. But for showing someone their settings in a familiar order, mapping iteration is useful and doesn’t require changing the file format.

## How do I deserialize an ordered map in Rust?

Pick the collection by the order you want. A [`HashMap`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.iter) iterates in arbitrary order. A [`BTreeMap`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html) iterates in key order. Neither can recover the order of the input by iterating the result. Parse into `Mapping` first if the order on disk is what matters.

A `Mapping` key is a `Value`, not necessarily a string. The variation shows integer keys: use `as_i64()` to read those keys instead of `as_str()`. When you don’t know whether the root node is a mapping, deserialize into `Value` and check `as_mapping()` before iterating it. When the order of entries isn’t enough and you need to edit the file without losing comments, read a `Document` instead of rebuilding the text from parsed values.
