Skip to content

Flatten and Unflatten Complex JSON #228

@akm151

Description

@akm151

I have these lines of code :

var jsonData = new JArray();
                var reader = new ChoParquetReader(stream)
                    .Configure(c => c.ThrowAndStopOnMissingField = false)
                    .Configure(c => c.NestedKeySeparator = '/');
                foreach (var e in reader)
                {
                    var unflatten = e.ConvertToNestedObject('/');
                    unflatten.flavours = (((string)unflatten.flavours) ?? "").Split(';');
                    unflatten.batters.category = (((string)unflatten.batters.category) ?? "").Split(';');    
                    jsonData.Add(JObject.FromObject(unflatten));

                }
                return JsonConvert.SerializeObject(jsonData);

and my Json is

[
    {
      "id": "4b5260d2-e088-4546-a315-b9c4b274406f",
      "type": "donut",
      "name":"cake",
      "flavours": " chocolate ; blueberry ; vanilla",
      "batters/topping":  "glazed",
       "batters/category": " eggless;flavoured"  
    }
]

my expected output:

[
    {
      "id": "4b5260d2-e088-4546-a315-b9c4b274406f",
      "type": "donut",
      "name":"cake",
      "flavours": ["chocolate","blueberry","vanilla"],
      "batters": {
        "topping":"glazed",
        "category":[ "eggless","flavoured"]
      }     
    }
]

Basic requirement while flattening and unflattening is that, if the value of a property is list or array of primitive type then while flattening we will merge the list or array to a ';' separated string and while unflattening we will split the ';' separated string to a list or array.
Note: the JSON showed here is a sample, originally I have a large JSON array and each object has lot's of properties so using LINQ solution is not feasible. Also I am looking for a generic solution as I have multiple entities of different types with similar properties.(just a change in name)
Eg: cake, chocolate, chips, cookies and so on. SO looking for a generic solution.
Please comment if further details are required.
Thanks for your interest in the question.

Looking forward to hearing from you @Cinchoo @neuli1980 @dbeattie1971

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions