Convert YAML to JSON in C#
The code for the options above. It produces the same JSON as the page:
Values that change on the way
Without WithAttemptingUnquotedStringTypeDeserialization(), YamlDotNet returns every value as a string, so the JSON has "8080" instead of 8080. With it, each unquoted scalar is tried as a number or boolean, and some of them do not come out the way they were written:
| YAML | JSON | Why |
|---|---|---|
0755 | 755 | Read as a decimal integer; the leading zero is not octal. |
0xFFFF | -1 | Hex is tried as byte, then short, and hex parsing of a short reads FFFF as -1. |
1.1234567891 | 1.1234568 | Non-integers become float when they fit, which keeps about 7 significant digits. |
1.10 | 1.1 | A version number is a number to YAML. Quote it: "1.10". |
99999999999999999999 | 1E+20 | Too big for ulong, so it becomes a float. |
yes, on, NO | strings | Only true, True, TRUE and the same three spellings of false are booleans; YAML 1.1's yes/no/on/off are not. |
0o17, 1_000 | strings | These YAML 1.2 forms are not parsed as numbers. |
.inf, .nan | error | They become float infinity and NaN, which JsonSerializer refuses to write unless you allow named floating-point literals. |
"0755", '1.10' | strings | Quoted values (and > folded blocks) always stay strings. |
Keys are never converted: 1: one gives the key "1". An empty value, ~ and null become null in both modes.
Other things to know
- Several documents.
Deserializer.Deserializereads one document and then expects the end of the stream, so a file with---between documents (a Kubernetes manifest with a Deployment and a Service) fails withExpected 'StreamEnd', got 'DocumentStart'. The page then reads the documents one by one, as the C# above shows, and returns a JSON array. - Duplicate keys are allowed by default: the last value wins, in the place of the first key.
WithDuplicateKeyChecking()makes them an error instead. - Anchors and aliases (
&labels,*labels) are expanded, so the JSON repeats the value. An alias before its anchor is an error, and an alias inside its own anchor makes a cycle thatJsonSerializerrefuses. Merge keys (<<: *base) are not merged unless you read throughMergingParser; by default<<is just a key. - Tags such as
!!str,!!int,!!floatand!!boolpick the .NET type. Any other tag, including CloudFormation's!Refand!Sub, fails with "Encountered an unresolved tag" unless you register it withWithTagMapping. - Complex keys (a mapping or a list used as a key, written with
?) deserialize fine, but JSON only has string keys, soJsonSerializerthrows aNotSupportedException. - Comments are dropped; JSON has none.
FAQ
Should I use typed or string values?
Typed values give the JSON most people expect, but check the list above: version numbers, zip codes and IDs with leading zeros change. For configuration you bind to C# classes, strings are safe, because the binder converts them to the property types.
Can I deserialize YAML straight into my own classes?
Yes, and it is usually better: deserializer.Deserialize<Config>(yaml) converts each value to the property's type, so port: 8080 becomes an int and version: 1.10 can stay a string.
Does .NET read YAML configuration?
Not out of the box. ASP.NET Core reads JSON, XML, INI, environment variables and command-line arguments; YAML needs a community configuration provider.
How do I convert YAML to JSON in C#?
Deserialize the YAML to object with YamlDotNet's DeserializerBuilder, then serialize that object with System.Text.Json's JsonSerializer.Serialize. Add WithAttemptingUnquotedStringTypeDeserialization() to get numbers and booleans instead of strings.
Why are all my numbers strings in the JSON?
YamlDotNet's deserializer returns every scalar as a string when the target type is object. WithAttemptingUnquotedStringTypeDeserialization() turns unquoted numbers, true, false and null into typed values.
Why does YamlDotNet fail on a file with several documents?
Deserializer.Deserialize reads one document and then expects the end of the stream, so a second document (after ---) fails with "Expected 'StreamEnd', got 'DocumentStart'". Read the documents one by one with a Parser, as the page's C# does.
Is my YAML uploaded?
No. The converter runs in your browser.