Recursive AI

Look up a nested YAML value by JSON Pointer in Rust

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

Call get_pointer with a path such as /app/ports/1 to read the second port without changing the YAML.

Terminal
cargo add oneyaml
RUST
use oneyaml::Document;
 
fn main() -> Result<
    (), Box<dyn std::error::Error>,
> {
    let yaml = "app:\n  ports: [80, 443]\n";
    let doc = Document::parse(yaml)?;
    let node =
        doc.get_pointer("/app/ports/1")?;
    let port = node.as_u64()
        .ok_or("not a u64")?;
    println!("{port}");
    Ok(())
}

Prints the second port:

Text
443

A pointer that names nothing returns a PatchError with kind Path because reads and patches share the pointer API. The example uses Rust 1.85 or later.

Unzip the example, then cargo run.

Variations

Use the empty pointer to select the root. On the same doc, look up app and its ports list from that root:

RUST
let root = doc.get_pointer("")?;
let app = root.get("app").ok_or("missing app")?;
println!("{}", app.get("ports").is_some());
Text
true

The short answer

With oneyaml-rust, there’s no patch to build or apply and no need to convert YAML to JSON.

How do JSON Pointer paths pick a nested YAML value?

Each slash starts another step. For a YAML mapping, the step names a key by its text; for a sequence, it gives a zero-based index. /app/ports/1 goes through the app and ports keys, then picks the second sequence entry. If ports were a mapping instead, that same last step would look for the key 1 as text. The node you reach, not the spelling of the token, decides how the token is read.

In RFC 6901 syntax, a slash inside a key is ~1 and a tilde is ~0. For example, /app/owner~1team means the key owner/team within app. The empty string selects the root; / selects a key whose name is empty. Unlike a query that can match several nodes, a pointer describes one location.

What happens if the pointer’s value is missing or isn’t a number?

Keep lookup and conversion separate. get_pointer returns a Result: Invalid means the path text isn’t a valid pointer and Path means it doesn’t resolve. A valid path to a string or a list can succeed, but as_u64() then returns None. This lets you give a type error instead of reporting every failure as a missing field.

A YAML pointer can reach a value through an alias; the returned node is the anchored value. If two keys match the same token, the lookup returns RefusedAmbiguous rather than choosing one. Both behaviors are documented on the pinned get_pointer API.

All oneyaml Rust recipes