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.
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));
{ "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,JsonValueandJsonElementare all supported targets.JsonDocumentisn’t, because a member of a model can’t dispose it; useJsonElement.- JSON is valid YAML 1.2, so
YamlSerializer.DeserializeandYamlDocument.Parseread JSON text directly. - For typed data, skip the tree: deserialize YAML into your type and serialize it with
JsonSerializer.