You can use the Newtonsoft.Json NuGet package to deserialize the JSON structure into a dynamic object, and then recursively iterate over the properties and values to flatten the structure. Here is an example implementation:
using Newtonsoft.Json.Linq;
public static class JsonFlattener
{
public static IDictionary<string, object> Flatten(string json)
{
var obj = JObject.Parse(json);
var flat = new Dictionary<string, object>();
Flatten(null, obj, flat);
return flat;
}
private static void Flatten(string prefix, JToken token, IDictionary<string, object> flat)
{
switch (token.Type)
{
case JTokenType.Object:
foreach (var pair in ((JObject)token))
{
Flatten(GetName(prefix, pair.Key), pair.Value, flat);
}
break;
case JTokenType.Array:
var index = 0;
foreach (var item in ((JArray)token))
{
Flatten(GetName(prefix, index.ToString()), item, flat);
index++;
}
break;
default:
flat.Add(prefix, ((JValue)token).Value);
break;
}
}
private static string GetName(string prefix, string name)
{
return string.IsNullOrEmpty(prefix) ? name : $"{prefix}.{name}";
}
}
To use the flattener, simply pass a JSON string to the Flatten method:
var json = "{ \"name\": \"John\", \"age\": 30, \"address\": { \"city\": \"New York\", \"state\": \"NY\" }, \"languages\": [ \"English\", \"Spanish\", \"French\" ] }";
var flat = JsonFlattener.Flatten(json);
foreach (var pair in flat)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
This will output:
name: John
age: 30
address.city: New York
address.state: NY
languages.0: English
languages.1: Spanish
languages.2: French
Note that the flattener uses dot notation to concatenate property names. This can be changed to suit your needs.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-09-27 11:00:00 +0000
Seen: 8 times
Last updated: Oct 12 '21
How can you ensure the safe operation of an Apache container on Kubernetes?
How can I use VS Code and R to create plots?
How can folders be created for each month using react pdf?
What is the meaning of the term deprecated with regards to react-google-login?
How can I use .populate() in Mongoose to select specific fields?
What explains the variation in performance between the benchmark's C version and its AVX2 version?
What is the process for preserving all Docker images and transferring them to a different device?