Created
November 9, 2017 16:10
-
-
Save jennings/5e66c14ae370850c30bc537174679454 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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