简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM