Smooth nested dictionary <string, object>

I am deserializing some nested JSON with the following:

string json = @"{ ""name"": ""charlie"", ""someID"": 123, ""level1"" : { ""name"": ""charlie 1"", ""someID"": 456 } }"; JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary<string, object> data = serializer.Deserialize<Dictionary<string, object>>(json); 

Once this is done, the meanings of each dictionary key can be a different Dictionary, etc., on several levels.

What I would like to do is flatten the tiered data, so this is just a flat array / list, only with the JSON attribute names and their values. So I get something like this:

 name, "charlie" someID, 123 name, charlie 1 someID, 456 

I followed the path of using SelectMany (), etc., but could not argue with him to do what I followed.

I was kind of waddling with things like this:

 var obj = data.Values.SelectMany<object, Dictionary<string, object>>(x => x); 

But I can not satisfy the compiler. Yes, I am lost.

I am using .NET 3.5.

+1
c # linq
source share
2 answers
 Func<Dictionary<string, object>, IEnumerable<KeyValuePair<string, object>>> flatten = null; flatten = dict => dict.SelectMany(kv => kv.Value is Dictionary<string,object> ? flatten((Dictionary<string,object>)kv.Value) : new List<KeyValuePair<string,object>>(){ kv} ); var flatList = flatten(data).ToList(); 
+3
source share

You need recursion:

 IEnumerable<Tuple<string, string>> Flatten(this IDictionary dict) { foreach(DictionaryEntry kvp in dict) { var childDictionary = kvp.Value as IDictionary; if(childDictionary != null) { foreach(var tuple in childDictionary.Flatten()) yield return tuple; } else yield return Tuple.Create(kvp.Key.ToString(), kvp.Value.ToString()); } } // Usage: var flatList = data.Flatten().ToList(); 

In .NET 3.5, you can use KeyValuePair<string, string> instead of Tuple<string, string> .

Note that there is no KeyValuePair.Create , you need to use new KeyValuePair<string, string>(kvp.Key.ToString(), kvp.Value.ToString()) .

+3
source share

All Articles