YamlDocument
Definition
Namespace: Corvus.Text.Json.Yaml
Assembly: Corvus.Text.Json.dll
Provides methods for parsing YAML content and converting it to ParsedJsonDocument instances or JSON strings.
public static class YamlDocument
Inheritance
Object → YamlDocument
Methods
| Method | Description |
|---|---|
Convert(ReadOnlySpan<byte>, Utf8JsonWriter, YamlReaderOptions) static |
Converts UTF-8 YAML bytes to JSON, writing the output to the specified Utf8JsonWriter. |
ConvertToJsonString static |
Converts UTF-8 YAML bytes to a JSON string. |
ConvertToYaml static |
Converts a JSON element to YAML, writing the output to the specified IBufferWriter. |
ConvertToYamlString static |
Converts a JSON element to a YAML string. |
EnumerateEvents static |
Enumerates the YAML parse events from UTF-8 YAML bytes, invoking the specified callback for each event. |
Parse static |
Parses UTF-8 YAML bytes and returns a ParsedJsonDocument containing the equivalent JSON representation. |
ParseAsync(Stream, YamlReaderOptions, CancellationToken) static |
Parses UTF-8 YAML from a Stream asynchronously and returns a ParsedJsonDocument... |
Examples
Parse YAML into a ParsedJsonDocument<TElement>, or convert between YAML and JSON string representations.
using Corvus.Text.Json;
using Corvus.Text.Json.Yaml;
string yaml = """
name: Alice
age: 30
hobbies:
- reading
- cycling
""";
using ParsedJsonDocument<JsonElement> doc = YamlDocument.Parse<JsonElement>(yaml);
string name = (string)doc.RootElement.GetProperty("name"u8);
// name: "Alice"
Converting YAML to a JSON string
string json = YamlDocument.ConvertToJsonString(yaml);
// json: {"name":"Alice","age":30,"hobbies":["reading","cycling"]}
Converting JSON to YAML
string yamlOutput = YamlDocument.ConvertToYamlString(
"""{"name":"Alice","age":30,"hobbies":["reading","cycling"]}""");
// yamlOutput:
// name: Alice
// age: 30
// hobbies:
// - reading
// - cycling
Multi-document streams
Parse a YAML stream containing multiple documents as a JSON array:
string multiDoc = """
---
name: Alice
---
name: Bob
""";
using ParsedJsonDocument<JsonElement> docs = YamlDocument.Parse<JsonElement>(multiDoc,
new YamlReaderOptions { DocumentMode = YamlDocumentMode.MultiAsArray });
int count = docs.RootElement.GetArrayLength(); // 2
Schema selection
// Use the JSON schema (all scalars except null, true, false, and numbers are strings)
string json = YamlDocument.ConvertToJsonString(yaml,
new YamlReaderOptions { Schema = YamlSchema.Json });
// Use the Failsafe schema (everything is a string)
string failsafe = YamlDocument.ConvertToJsonString(yaml,
new YamlReaderOptions { Schema = YamlSchema.Failsafe });
Applies To
| Product | Versions |
|---|---|
| .NET | 9, 10 |
| .NET Standard | 2.0, 2.1 |
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests.
Open an issue