Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jennings/5e66c14ae370850c30bc537174679454 to your computer and use it in GitHub Desktop.
Save jennings/5e66c14ae370850c30bc537174679454 to your computer and use it in GitHub Desktop.
// paste this into a LINQPad C# Program
void Main()
{
var str = @"Key1=Value1
Key2:Key3=Value2";
var strings = str.Split(new []{"\r\n"}, StringSplitOptions.None)
.Select(s => s.Split(new[]{'='}, 2));
var result = Merge(strings);
JsonConvert.SerializeObject(result, new JsonSerializerSettings{ Formatting = Newtonsoft.Json.Formatting.Indented }).Dump();
}
Dictionary<string, object> Merge(IEnumerable<string[]> strings)
{
var dict = new Dictionary<string, object>();
foreach (var pair in strings)
{
Insert(dict, pair[0], pair[1]);
}
return dict;
}
void Insert(Dictionary<string, object> dict, string key, string value)
{
var parts = key.Split(new[]{':'}, 2);
if (parts.Count() == 1)
{
dict.Add(key, value);
return;
}
if (!dict.ContainsKey(parts[0]))
{
dict.Add(parts[0], new Dictionary<string, object>());
}
var subdict = (Dictionary<string, object>)dict[parts[0]];
Insert(subdict, parts[1], value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment