简要示例
CSV文件:
name, source, target
John , A , None
Emma , B , A
Mike , C , A
理论上对应的JSON文件:
{
"comment": "example code",
"nodes": [
{
"name": John,
"source" : A
},
{
"name": Emma ,
"source" : B
},
{
"name": Mike ,
"source" : C
}
],
"links": [
{
"source": B,
"target": A
},
{
"source": C,
"target": A
}
]
}
结果图概念:
B -> A <- C
上面的JSON文件不是绝对的。它可以有各种模式。上面的例子非常基本。
我希望有一个软件或库可以轻松地将CSV数组转换为JSON文件或类似的东西。
我有很多CSV文件,我想转换成JavaScript图表,但首先我需要一个数据结构良好的JSON输入文件。我想自动化JSON文件构建。
答案 0 :(得分:0)
以下是使用csvtojson的示例。
const csv = require('csvtojson');
const csvFilePath = 'test.csv';
var data = [];
csv().fromFile(csvFilePath)
.on('json', (jsonObj) => {
data.push(jsonObj);
})
.on('done', (error) => {
if (error) {
console.error(error);
} else {
formatData(data);
}
});
function formatData(data) {
var formatted = {
comment: "hello",
nodes: [],
links: []
};
data.forEach(function(r){
//check for your empty or 'None' fields here
if(r.name && r.source){
formatted.nodes.push({ name: r.name, source: r.source });
}
if (r.source && r.target) {
formatted.links.push({ source: r.source, target: r.target });
}
});
//do something with the finished product
console.log(formatted);
}
答案 1 :(得分:0)
以下是使用jq
的解决方案如果文件filter.jq
包含
[
split("\n") # split string into lines
| [.[0] | split(",")[] | gsub("[[:space:]]+";"")] as $headers # split header
| (.[1:][] | split(",")) # split data rows
| select(length>0) # get rid of empty lines
| [ [ $headers, map(gsub("[[:space:]]+";"")) ] #
| transpose[] # assemble objects
| {key:.[0], value:.[1]} # from keys and values
] | from_entries #
]
| {
"comment":"example code", # convert objects
"nodes": map({name,source}), # to requested format
"links": map(select(.target!="None")|{source,target}) #
}
和data
包含
name, source, target
John , A , None
Emma , B , A
Mike , C , A
然后命令
jq -M -R -s -r -f filter.jq data
将产生
{
"comment": "example code",
"nodes": [
{
"name": "John",
"source": "A"
},
{
"name": "Emma",
"source": "B"
},
{
"name": "Mike",
"source": "C"
}
],
"links": [
{
"source": "B",
"target": "A"
},
{
"source": "C",
"target": "A"
}
]
}