Json Data in present format: currently I am getting data from a database in the following format which I am storing in a DataTable.
Database format
var data1 =
[{“TheatreName”:”AMEA”,”Country”:”CANADA”,”Riskcount”:50},{“TheatreName”:”AMEA”,”Country”:”UK”,”Riskcount”:30},{“TheatreName”:”AMER”,”Country”:”Japan”,”Riskcount”:80},{“TheatreName”:”AMER”,”Country”:”US”,”Riskcount”:90},{“TheatreName”:”APAC”,”Country”:”Bangladesh”,”Riskcount”:4},{“TheatreName”:”APAC”,”Country”:”Hong Kong”,”Riskcount”:12},{“TheatreName”:”APAC”,”Country”:”India”,”Riskcount”:126}]
I want to convert it into a JSON object in the following format.
var data =
{
"APAC": {
"Bangladesh": 30,
"Hong Kong": 40,
"India":50
},
"AMEA": {
"UK": 30,
"CANADA": 50
},
"AMER": {
"Japan": 80,
"US": 90
}
}
2
If you already have class for above properties , so it already in list of item you need to write Linq query group by TheatreName
var groupedData = oldjson.GroupBy(t => t.TheatreName);
groupedData serialize/convert the object
0
Using arrow function in your data apply this condition resultdata similer data1.
var chartData = [];
var resultData =
[{"TheatreName":"AMEA","Country":"CANADA","Riskcount":50},{"TheatreName":"AMEA","Country":"UK","Riskcount":30},{"TheatreName":"AMER","Country":"Japan","Riskcount":80},{"TheatreName":"AMER","Country":"US","Riskcount":90},{"TheatreName":"APAC","Country":"Bangladesh","Riskcount":4},{"TheatreName":"APAC","Country":"Hong Kong","Riskcount":12},{"TheatreName":"APAC","Country":"India","Riskcount":126}]
Apply this function
var data ={};
resultData.forEach(item=>{
if(!data[item.TheatreName]){
data[item.TheatreName]={};
}
data[item.TheatreName][item.Country]=item.Riskcount;
});