Harsh Raj
Harsh Raj

Reputation: 89

How to make json file using an array of strings?

I have a array of string. I want to make a JSON file from it, mapping it to a hierarchy of nested objects using the strings as property names and final value. For example, if array contains {"A", "B", "C", "D"}, then the resultant JSON file should look like

{
  "A": {
    "B": {
      "C": "D"
       }
    }
}

Is there any way to do that?

Upvotes: 0

Views: 446

Answers (1)

dbc
dbc

Reputation: 116615

You can generate a nested set of JSON objects from an array of strings using LINQ and a JSON serializer (either or ) as follows:

var input = new[]{"A","B","C","D"};

var data = input
    .Reverse()
    .Aggregate((object)null, (a, s) => a == null ? (object)s : new Dictionary<string, object>{ { s, a } });

var json = JsonConvert.SerializeObject(data, Formatting.Indented);

The algorithm works by walking the incoming sequence of strings in reverse, returning the string itself for the last item, and returning a dictionary with an entry keyed by the current item and valued by the previously returned object for subsequent items. The returned dictionary or string subsequently can be serialized to produce the desired result.

Demo fiddle here.

Upvotes: 2

Related Questions