How to read yaml without serialization #925
Unanswered
JWJUN233233
asked this question in
Q&A
Replies: 1 comment
-
You can use the parser to read the yaml quick and dirty to check if a key exists and interact with a list directly. Here's a quick example. Lists are more complicated, but not by much. using YamlDotNet.Core;
using YamlDotNet.Core.Events;
var listLevel = 0;
string? lastScalar = null;
var yaml = @"
a: b
c: d
e: f
list1:
- list1 item 1 (just a simple scalar)
- list1 item 2 (it's a list in a list):
- nested list for list 1
list2:
- list2 item 2 (it's a list in a list):
- nested list for list 2
";
var parser = new Parser(new StringReader(yaml));
while (parser.MoveNext())
{
var token = parser.Current;
if (token is Scalar scalar)
{
lastScalar = scalar.Value;
if (scalar.IsKey)
{
if (scalar.Value == "c")
{
Console.WriteLine("c key exists");
}
if (scalar.Value == "d")
{
Console.WriteLine("d matched but shouldn't");
}
}
}
else if (token is SequenceStart start)
{
listLevel += start.NestingIncrease;
Console.WriteLine("we're starting a list that was keyed as {0}. New level: {1}", lastScalar, listLevel);
}
else if (token is SequenceEnd end)
{
listLevel += end.NestingIncrease;
Console.WriteLine("End of list. New level: {0}", listLevel);
}
} Results in:
Does this help? |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
i wonder how to know if there is a key in yaml.
i wonder how to read a list directly.
Beta Was this translation helpful? Give feedback.
All reactions