I have a json-object in C# (represented as a Newtonsoft.Json.Linq.JObject object) and I need to flatten it to a dictionary. Let me show you an example of what I mean:
{ "name": "test", "father": { "name": "test2" "age": 13, "dog": { "color": "brown" } } }
This should yield a dictionary with the following key-value-pairs:
["name"] == "test", ["father.name"] == "test2", ["father.age"] == 13, ["father.dog.color"] == "brown"
How can I do this?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
JObject jsonObject=JObject.Parse(theJsonString); IEnumerable<JToken> jTokens = jsonObject.Descendants().Where(p => !p.HasValues); Dictionary<string, string> results = jTokens.Aggregate(new Dictionary<string, string>(), (properties, jToken) => { properties.Add(jToken.Path, jToken.ToString()); return properties; });
I had the same requirement of flattening a nested json structure to a dictionary object. Found the solution here.
As of .NET Core 3.0 JsonDocument
is a way (Json.NET is not needed). I'm sure this will get easier.
using System.Linq; using System.Text.Json; (...) public static Dictionary<string, JsonElement> GetFlat(string json) { IEnumerable<(string Path, JsonProperty P)> GetLeaves(string path, JsonProperty p) => p.Value.ValueKind != JsonValueKind.Object ? new[] { (Path: path == null ? p.Name : path + "." + p.Name, p) } : p.Value.EnumerateObject() .SelectMany(child => GetLeaves(path == null ? p.Name : path + "." + p.Name, child)); using (JsonDocument document = JsonDocument.Parse(json)) // Optional JsonDocumentOptions options return document.RootElement.EnumerateObject() .SelectMany(p => GetLeaves(null, p)) .ToDictionary(k => k.Path, v => v.P.Value.Clone()); //Clone so that we can use the values outside of using }
A more expressive version is shown below.
using System.Linq; using System.Text.Json; (...) var json = @"{ ""name"": ""test"", ""father"": { ""name"": ""test2"", ""age"": 13, ""dog"": { ""color"": ""brown"" } } }"; var d = GetFlat(json); var options2 = new JsonSerializerOptions { WriteIndented = true }; Console.WriteLine(JsonSerializer.Serialize(d, options2));
{ "name": "test", "father.name": "test2", "father.age": 13, "father.dog.color": "brown" }
using System.Linq; using System.Text.Json; (...) static Dictionary<string, JsonElement> GetFlat(string json) { using (JsonDocument document = JsonDocument.Parse(json)) { return document.RootElement.EnumerateObject() .SelectMany(p => GetLeaves(null, p)) .ToDictionary(k => k.Path, v => v.P.Value.Clone()); //Clone so that we can use the values outside of using } } static IEnumerable<(string Path, JsonProperty P)> GetLeaves(string path, JsonProperty p) { path = (path == null) ? p.Name : path + "." + p.Name; if (p.Value.ValueKind != JsonValueKind.Object) yield return (Path: path, P: p); else foreach (JsonProperty child in p.Value.EnumerateObject()) foreach (var leaf in GetLeaves(path, child)) yield return leaf; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With