Home > Software design >  how to make a duplicate json object's property a parent and merge it's other properties as
how to make a duplicate json object's property a parent and merge it's other properties as

Time:05-29

We have json format as shown below and want to normalize it as given in expected output.

Input format: [ { "country": "Germany", "name": "2010", "value": 40632 }, { "country": "United States", "name": "2010", "value": 0 }, { "country": "United States", "name": "2000", "value": 45986 }, { "country": "United States", "name": "1990", "value": 37060 }, { "country": "France", "name": "2010", "value": 36745 }, { "country": "France", "name": "2000", "value": 34774 } ]

Expected output :

[ { "name": "Germany", "series": [ { "name": "2010", "value": 40632 } ] }, { "name": "United States", "series": [ { "name": "2010", "value": 0 }, { "name": "2000", "value": 45986 }, { "name": "1990", "value": 37060 } ] }, { "name": "France", "series": [ { "name": "2010", "value": 36745 }, { "name": "2000", "value": 34774 } ] } ]

CodePudding user response:

try this

    var jArr = JArray.Parse(input);
    var groupedData = jArr.GroupBy(a => a["country"]).ToList();

    var outputArr = new JArray();
    foreach (var item in groupedData)
    {
        JObject obj = new JObject();
        obj.Add("name", item.Key);
        var arr = new JArray();
        obj.Add("series", arr);
        foreach (var jObj in item)
        {
            JObject newObj = new JObject();
            newObj.Add("name", jObj["name"]);
            newObj.Add("value", jObj["value"]);
            arr.Add(newObj);
        }
        outputArr.Add(obj);
    }

    var output = outputArr.ToString();
  •  Tags:  
  • json
  • Related