Recursive AI

Convert YAML to JSON and back

All oneyaml C# recipes

Turn a YAML file into JSON, or JSON into YAML. YamlSerializer reads into and writes from JsonNode and JsonElement, so System.Text.Json does the JSON side.

C#
using System.Text.Json;
using System.Text.Json.Nodes;
using OneYaml;
 
// YAML to JSON: read into a JsonNode, write it with System.Text.Json.
JsonNode? json = YamlSerializer.Deserialize<JsonNode>("""
    name: web
    ports: [80, 443]
    tls: true
    owner: ~
    """);
Console.WriteLine(json!.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
 
// JSON to YAML: JSON is valid YAML 1.2, so read it and write YAML.
JsonNode? fromJson = JsonNode.Parse("""{"name": "web", "ports": [80, 443], "env": {"LOG": "info"}}""");
Console.Write(YamlSerializer.Serialize(fromJson));
Text
{
  "name": "web",
  "ports": [
    80,
    443
  ],
  "tls": true,
  "owner": null
}
name: web
ports:
  - 80
  - 443
env:
  LOG: info

Good to know

  • The keys keep the file’s order in both directions.
  • JsonNode, JsonObject, JsonArray, JsonValue and JsonElement are all supported targets. JsonDocument isn’t, because a member of a model can’t dispose it; use JsonElement.
  • JSON is valid YAML 1.2, so YamlSerializer.Deserialize and YamlDocument.Parse read JSON text directly.
  • For typed data, skip the tree: deserialize YAML into your type and serialize it with JsonSerializer.