Ask Your Question
0

How can I use c# to flatten a Json structure in a generic manner?

asked 2022-09-27 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-10-12 20:00:00 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-09-27 11:00:00 +0000

Seen: 8 times

Last updated: Oct 12 '21