Javascript 通过合并数据集到JSON树
假设我有下面的数据集Javascript 通过合并数据集到JSON树,javascript,asp.net,json,c#-4.0,serialization,Javascript,Asp.net,Json,C# 4.0,Serialization,假设我有下面的数据集 ╔═════════════╦═══════════════╦═══════╗ ║ Category ║ Item ║ Color ║ ╠═════════════╬═══════════════╬═══════╣ ║ Electronics ║ Mobile ║ Black ║ ║ Electronics ║ Mobile ║ Green ║ ║ Electronics ║ Laptop ║ Black ║
╔═════════════╦═══════════════╦═══════╗
║ Category ║ Item ║ Color ║
╠═════════════╬═══════════════╬═══════╣
║ Electronics ║ Mobile ║ Black ║
║ Electronics ║ Mobile ║ Green ║
║ Electronics ║ Laptop ║ Black ║
║ HomeNeeds ║ VaccumCleaner ║ white ║
║ HomeNeeds ║ Refrigerator ║ Red ║
║ Wearable ║ AppleWatch ║ Red ║
╚═════════════╩═══════════════╩═══════╝
我想将其转换为类似于以下JSON格式的格式,以便可以加载到treeview控件中。最好的方法是什么?主要区别在于合并相同的类别或项目!
我可以在C中逐个解析节点,检查它和前一个节点,如果相同,则合并它!并手动创建,但除了这个漫长而复杂的过程,还有其他替代方法吗
{
"Categories" : [
{"Electronics" : [
{"Mobile" : [
{"color":"Black"},
{"color":"Green"}
]},
{"Laptop":[
{"color":"Black"}
]}
]},
{"HomeNeeds":[
{"VaccumCleaner": [
{"color":"white"}
]},
{"Refrigerator":[
{"color": "Red"}
]}
]},
{"Wearable":[
{"Applewatch":[
{"color":"Red"}
]}
]}
]
}
使用数组
var products = new Array(); // using new Array() to avoid mess
products =
[
[ // Home Needs
[
"Refrigerator",
"red",
"$500",
],
[
"VacuumCleaner",
"white",
"$50",
]
],
[ // Wearable
[
"Applewatch",
"Red",
"$14, 000",
],
],
]
下面是一个关于如何使用此功能的示例
function getInfoOn(category,nameofappliance) { // 0 for category is home needs, etc
for (var i=0; i < products[category].length; i++) {
for(var l=0; l < products[i].length; l++) {
for (var b=0; b < i[category][l].length; b++) {
console.log('Name: '+ i[category][l][0]);
console.log('Price: '+i[category][l][2]);
}
}
}
}
请注意,上述代码仅用于示例。它应该可以正常工作,但我可能在写它的时候出错了。这只是为了表明我的观点 尝试使用Json.NET框架将数据集转换为Json字符串
using Newtonsoft.Json;
DataTable MyData = new DataTable();
string Output = "";
Output = JsonConvert.SerializeObject(MyData, Formatting.Indented);
你需要的是一群人,不是吗 试试林克。这只是一种未经测试的方法,但可以为您提供从何处开始的想法:
var results = from c in dataset
group c by c.Category into cGrouped
select new {
Category = cGrouped.Category,
Items = from i in cGrouped
group i by i.Item into iGrouped
select new {
Item = iGrouped.Item
Colors = from cl in iGrouped
group cl by cl.Color into clGrouped
select new {
Color = cl.Color
}
}
};
然后使用控制器的json ActionResult返回json:
return Json(results);
不需要进行合并。我意识到您可能正在用C做这件事,我将用Javascript向您展示答案,但我们知道C有数组、HashMaps和JSONSerializer类,所以这应该是合理的伪代码
var data = [
['Electronics', 'Mobile', 'Black'],
['Electronics', 'Mobile', 'Green'],
['Electronics', 'Laptop', 'Black'],
['HomeNeeds', 'VaccumCleaner', 'white'],
['HomeNeeds', 'Refigerator', 'Red'],
['Wearable', 'AppleWatch', 'Red']
];
function force(collection, key) {
if (!collection[key]) collection[key] = {};
return collection[key];
}
function tableToTree(data) {
var result = {};
data.forEach(function(item) {
force(force(result, item[0]), item[1]).color = item[2];
});
return result;
}
console.log(JSON.stringify(tableToTree(data)));
诀窍很简单。。。无论是哪种语言,你都需要能够说
result[category][item]["color"] = color;
…没有对你吼叫。然后可以使用一个可用的JSON序列化程序。代码应该易于阅读,即使它不是绝对性能最好的代码
如果速度很重要,或者你会经常这样做,那么构建一个集合只是为了序列化和解构它是非常昂贵的。花点时间为对象编写JSON编码器,它将执行弹出、推送和比较操作,并在整个集合中添加字符串。您有两种可能:1。你自己做,2。让数据库来完成这项工作 对于问题中显示的结果集,选择col1、col2、。。。按col1,col2。。。您可以通过以下方式对其进行解析:
=== simplified algorithm in pseudo code ===
init old column values to a unique value (e.g. null if not used)
loop over the result set:
test the columns from left to right:
if old column X <> column X
add column X and all values to the right to the datastructure
例如,假设从数据库返回的查询在每一行中都是这样的,这只是我们在这里需要的东西
var row = {'Category': 'value', 'Item': 'value', 'Color': 'value'}
您只需要javascript中的以下代码:
首先,构建一个空对象,如:
var object = {} or window.object = {}
然后在foreach或任何获取每行值的地方调用此代码
if(object['Category'] == undefined)
object['Category'] = {}
if(object['Category'][row['Category']] == undefined)
object['Category'][row['Category']] = {}
if(object['Category'][row['Category']][row['Item']] == undefined)
object['Category'][row['Category']][row['Item']] = []
object['Category'][row['Category']][row['Item']].push({
['Color'] : {[row['Color']]
})
我做了一个修改,只是最后一部分是数组rest is object,希望对您有所帮助,所有这行的意思都是这样的
object['Category'][row['Category']][row['Item']].push({['Color'] : {[row['Color']]})
你只需要确定它们是否存在,不要再构建它们了谢谢!但问题是如何将数据集转换为这个数组/JSON@罗伯特:你需要某种东西将数据表转换成数组吗?是的!但是我不需要像我在问题中问的那样!它意味着等级制度。在数据库中不一样!希望你能理解@罗伯特:是的,我喜欢。可能想托管一个SQL数据库。PHP可以将查询结果排序为数组。我可以将查询结果转换为数组,但这里的任务是将普通查询结果转换为树型数组。这意味着不允许重复。我不确定这是否有帮助,因为我们不知道数据的确切来源,即其原始形式,它只是一个想法。
object['Category'][row['Category']][row['Item']].push({['Color'] : {[row['Color']]})