我有这个用于sankey图的CSV文件,我想用JSON改进它,因为我的函数使用JSON格式但是我需要从CSV读取
CSV文件是这样的:
select t1.*
from table t1
inner join table t2 on t1.merge=t2.merge --self join
where t2.merge_order=1 --relate the 1st of each merge to each record in the merge
order by t2.name ASC, t1.merge_order ASC --the name in t2 will be the name from the 1st record, see where clause
和JSON文件表单应该是这样的,所以我的代码将能够读取它。
source,xPos,target,value
user1,0,user2,4
user2,1,user3,4
user1,0,user3,2
user5,user4,2
在示例中忽略了名称和链接,但这只是一个例子。
答案 0 :(得分:0)
没有简单的方法可以做到这一点。您需要实现自定义逻辑,如下所示。
var csv = "source,xPos,target,value\nuser1,0,user2,4\nuser2,1,user3,4\nuser1,0,user3,2\nuser5,user4,2";
var json = csv.split('\n').reduce(function(result, line, index) {
if (index > 0) { // Skip header.
var data = line.split(',');
if (data.length === 4) { // Skip rows with incomplete columns.
var containsSourceNode = result.nodes.some(function(node) { return node.name === data[0]; });
if (!containsSourceNode) {
result.nodes.push({
node : result.nodes.length,
name : data[0],
xpos : data[1]
});
}
var containsTargetNode = result.nodes.some(function(node) { return node.name === data[2]; });
if (!containsTargetNode) {
result.nodes.push({
node : result.nodes.length,
name : data[2],
xpos : data[1]
});
}
result.links.push({
source : result.nodes.filter(function(node) { return node.name === data[0]; })[0].node,
target : result.nodes.filter(function(node) { return node.name === data[2]; })[0].node,
value : data[3]
});
}
}
return result;
}, {
nodes : [],
links : []
});
document.body.innerHTML = '<pre>' + JSON.stringify(json, null, 2) + '</pre>';
var csv = "source,xPos,target,value\nuser1,0,user2,4\nuser2,1,user3,4\nuser1,0,user3,2\nuser5,user4,2";
var json = csv.split('\n').reduce(function(result, line, index) {
if (index > 0) { // Skip header.
var data = line.split(',');
if (data.length === 4) { // Skip rows with incomplete columns.
var containsSourceNode = result.cache[data[0]] != null;
if (!containsSourceNode) {
result.nodes.push(result.cache[data[0]] = {
node : result.size++,
name : data[0],
xpos : data[1]
});
}
var containsTargetNode = result.cache[data[2]] != null;
if (!containsTargetNode) {
result.nodes.push(result.cache[data[2]] = {
node : result.size++,
name : data[2],
xpos : data[1]
});
}
result.links.push({
source : result.cache[data[0]].node,
target : result.cache[data[2]].node,
value : data[3]
});
}
}
return result;
}, {
nodes : [],
links : [],
cache : {},
size : 0
});
delete json.cache;
delete json.size;
document.body.innerHTML = '<pre>' + JSON.stringify(json, null, 2) + '</pre>';