Home > Software engineering >  Convert tabular json data to d3 hierarchal data for pack chart
Convert tabular json data to d3 hierarchal data for pack chart

Time:03-13

I have a small dataset in JSON file which I want to convert into hierarchal data format to create a circular pack chart. This is my dataset:

{
"Marks": [
{"student": "Maria", "AI": 95, "DB": 77, "CG": 31, "ITP": 97, "LIT": 45},
{"student": "Sam", "AI": 85, "DB": 37, "CG": 39, "ITP": 45, "LIT": 55}
]
}

This is the output I am looking for:

{
"name": "Marks",
 "children": [
  { "name": "Maria",
 "children": [
  { "name": "AI" , "marks" : 95},
  { "name": "DB" , "marks" : 77},
  { "name": "CG" , "marks" : 35},
  { "name": "ITP" , "marks" : 97},
  { "name": "LIT" , "marks" : 45},
]
},
{ "name": "Sam",
 "children": [
  { "name": "AI" , "marks" : 85},
  { "name": "DB" , "marks" : 37},
  { "name": "CG" , "marks" : 39},
  { "name": "ITP" , "marks" : 45},
  { "name": "LIT" , "marks" : 55},
]
}
]
}


Any idea how I can proceed with this?

CodePudding user response:

try this

var newObj = {};
Object.keys(marks).forEach((key) => {
 newObj.name = key;
  newObj.children = [];
  var i = 0;
  marks[key].forEach((element) => {
    Object.keys(element).forEach((k) => {
      if (k == "student") newObj.children.push({ name: element[k], children: [] });
     else newObj.children[i].children.push({ name: k, marks: element[k] });
    });
    i  ;
  });
});

result

{
    "name": "Marks",
    "children": [
        {
            "name": "Maria",
            "children": [
                {
                    "name": "AI",
                    "marks": 95
                },
                {
                    "name": "DB",
                    "marks": 77
                },
                {
                    "name": "CG",
                    "marks": 31
                },
                {
                    "name": "ITP",
                    "marks": 97
                },
                {
                    "name": "LIT",
                    "marks": 45
                }
            ]
        },
        {
            "name": "Sam",
            "children": [
                {
                    "name": "AI",
                    "marks": 85
                },
                {
                    "name": "DB",
                    "marks": 37
                },
                {
                    "name": "CG",
                    "marks": 39
                },
                {
                    "name": "ITP",
                    "marks": 45
                },
                {
                    "name": "LIT",
                    "marks": 55
                }
            ]
        }
    ]
}
  • Related