---
title: "Convert YAML to JSON and back"
url: https://recursiveai.org/oneyaml/csharp/cookbook/yaml-to-json/
description: "Convert YAML to JSON in C# by reading it into a System.Text.Json JsonNode with OneYaml, and convert JSON back to YAML with YamlSerializer."
version: "1.2.1"
---

# Convert YAML to JSON and back

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.

```csharp
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`.
