-
-
Notifications
You must be signed in to change notification settings - Fork 345
/
YamlExtensions.cs
93 lines (87 loc) · 3.03 KB
/
YamlExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System.IO;
using System.Linq;
using YamlDotNet.Core;
using YamlDotNet.RepresentationModel;
using Newtonsoft.Json.Linq;
namespace CKAN.NetKAN.Extensions
{
internal static class YamlExtensions
{
public static YamlMappingNode[] Parse(string input)
{
return Parse(new StringReader(input));
}
public static YamlMappingNode[] Parse(TextReader input)
{
var stream = new YamlStream();
stream.Load(input);
return stream.Documents.Select(doc => doc?.RootNode as YamlMappingNode)
.OfType<YamlMappingNode>()
.ToArray();
}
/// <summary>
/// Convert a YAML object to a JSON object
/// </summary>
/// <param name="yaml">The input object</param>
/// <returns>
/// A JObject representation of the input data
/// </returns>
public static JObject ToJObject(this YamlMappingNode yaml)
{
var jobj = new JObject();
foreach (var kvp in yaml)
{
if ((string?)kvp.Key is string k)
{
switch (kvp.Value)
{
case YamlMappingNode obj:
jobj.Add(k, obj.ToJObject());
break;
case YamlSequenceNode array:
jobj.Add(k, array.ToJarray());
break;
case YamlScalarNode scalar:
jobj.Add(k, scalar.ToJValue());
break;
}
}
}
return jobj;
}
private static JArray ToJarray(this YamlSequenceNode yaml)
{
var jarr = new JArray();
foreach (var elt in yaml)
{
switch (elt)
{
case YamlMappingNode obj:
jarr.Add(obj.ToJObject());
break;
case YamlSequenceNode array:
jarr.Add(array.ToJarray());
break;
case YamlScalarNode scalar:
jarr.Add(scalar.ToJValue());
break;
}
}
return jarr;
}
private static JValue ToJValue(this YamlScalarNode yaml)
{
switch (yaml.Value)
{
case "null": return JValue.CreateNull();
case "true": return new JValue(true);
case "false": return new JValue(false);
// Convert unquoted integers to int type
default: return yaml.Style == ScalarStyle.Plain
&& int.TryParse(yaml.Value, out int intVal)
? new JValue(intVal)
: new JValue(yaml.Value);
}
}
}
}