Recursive AI

Select a nested YAML node with JSON Pointer in C#

OneYaml is a free, open-source YAML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Pass /spec/replicas to GetNode to read replicas under spec. For a slash inside a key, use ~1: /metadata/app~1owner selects app/owner under metadata.

Terminal
dotnet add package OneYaml

OneYaml targets .NET 8 and .NET 10; the zip uses .NET 10.

C#
using OneYaml;
 
using var doc = YamlDocument.Parse("""
    spec:
      replicas: 3
    metadata:
      app/owner: platform
    """);
var replicas = doc.GetNode("/spec/replicas");
Console.WriteLine(replicas.GetValue<int>());
var owner = doc.GetNode("/metadata/app~1owner");
Console.WriteLine(owner.GetValue<string>());

Prints the replica count, then the owner:

Text
3
platform

If GetNode throws a YamlException with category PatchPath, the path wasn’t found. For an optional value, use TryGet<T>; to check whether a path exists, use Contains.

Unzip the example, then dotnet run.

Variations

If you only want the owner string, use a typed lookup on the same document:

C#
Console.WriteLine(doc.Get<string>("/metadata/app~1owner"));
Text
platform

The short answer

Parse the YAML with YamlDocument.Parse and pass /spec/replicas to GetNode. Call GetValue<int>() on the selected node to read the count. For the key app/owner, pass /metadata/app~1owner and call GetValue<string>() on the result. The document stays YAML; “JSON” refers to the pointer syntax.

How do you escape a slash in a JSON Pointer?

Use ~1 for / and ~0 for ~, as defined by RFC 6901. A leading / starts a path step. /metadata/app/owner would therefore look for owner under a mapping at app, not a key named app/owner. Quoting the key in the YAML doesn’t change the pointer syntax.

When key holds a YAML key such as "app/owner", escape the tilde first and then the slash:

C#
var token = key.Replace("~", "~0").Replace("/", "~1");

Append the token to "/metadata/" for this example. Escaping slashes first would also escape the new tilde in ~1. Don’t escape the slashes that separate path steps.

Can you look up one nested YAML value in C# without a class?

Yes. The OneYaml editing guide distinguishes GetNode, which gives you a node to inspect, from Get<T>, which returns a scalar converted to a .NET type. Use GetNode when you want the same code to accept a mapping, a sequence, or a scalar and inspect its Kind; use Get<string> when you already know you need a string.

Keep the document alive while you use the node: a YamlNode is a view into its owning document, not a copy you can use after disposal.

All oneyaml C# recipes