我正在寻找一种向d3.js bubble chart提供来自我的MVC应用程序的数据的好方法。例如,标准气泡图需要表格中的嵌套数据:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{
"name": "CNN",
"size": 3938
}
]
},
{
"name": "graph",
"children": [
{
"name": "MTV",
"size": 3534
}
]
}
]
}
]
}
我在服务器端拥有的是对SQL数据库的linq查询:
var results = from a in db.Durations
where a.Category == "watch"
group a by a.Description
into g
select new
{
name = g.Key,
size = g.Select(d => new{d.Begin, d.End}).Sum(d => SqlFunctions.DateDiff("hh", d.Begin, d.End))
};
return Json(results, JsonRequestBehavior.AllowGet);
查询结果,解析为Json,如下所示:
[{"name":"CNN","size":1950},{"name":"MTV","size":1680}]
我对于实现正确格式化以及从查询结果中创建嵌套结构的好方法感到困惑。
感谢您的任何意见。
答案 0 :(得分:3)
将return语句替换为以下语句。
return Json(new
{
name = "Sites",
children = results
},
JsonRequestBehavior.AllowGet);
这将为您提供以下内容:
{
"name": "Sites",
"children": [
{
"name": "CNN",
"size": 1950
},
{
"name": "MTV",
"size": 1680
}
]
}
举个例子,假设每个网站都有一个额外的string Type
属性,其值为"News"
或"Music"
。然后你可以做到以下几点。
return Json(new
{
name = "Sites",
children = results.GroupBy(site => site.Type).Select(group => new
{
name = group.Key,
children = group
}
},
JsonRequestBehavior.AllowGet);
这会给你以下内容。
{
"name": "Sites",
"children": [
{
"name": "News",
"children": [
{
"name": "CNN",
"size": 1950
},
{
"name": "The Verge",
"size": 1600
}
]
},
{
"name": "Music",
"children": [
{
"name": "MTV",
"size": 1680
},
{
"name": "Pandora",
"size": 2000
}
]
}
]
}