我有一个CSV,在两个单独的列中都有坐标。
在将CSV转换为JSON时,我需要将它们组合到JSON对象内的数组中。我似乎找不到JavaScript或Python的解决方案(我愿意将两者用于结果)
由于坐标嵌套数组的格式,这不是JSON的简单CSV
输入:
CSV与此类似:
name,code, address,address,entries,exits,longitude,latitude
Lafayette,LF,"3601 Deer Hill",3481,3616,-122.123801,37.893394
12th St.,12,"1245 Broadway",13418,13547,-122.271604,37.803664
输出:
[
{
"name": "Lafayette",
"code": "LF",
"address": "3601 Deer Hill",
"entries": "3481",
"exits": "3616",
"coordinates": [
-122.123801,
37.893394
]
},
{
"name": "12th St.)",
"code": "12",
"address": "1245 Broadway",
"entries": "13418",
"exits": "13547",
"coordinates": [
-122.271604,
37.803664
]
}
]
这是一个示例数据集,我正在尝试复制坐标的结构,并以逗号分隔的数组配对。
答案 0 :(得分:0)
从csv中读取数据,然后按预期方式将其转换为JSON,请尝试以下操作:
//let csv is the CSV file with headers
function csvJSON(csv) {
let lines = csv.split("\n");
let result = [];
let headers = lines[0].split(",");
for (let i = 1; i < lines.length; i++) {
let obj = {};
let coordinates = [];
let currentline = lines[i].split(",");
for (let j = 0; j < headers.length; j++) {
if (headers[j] == 'longitude' || headers[j] == 'latitude') {
coordinates.push(currentline[j])
obj['coordinates'] = coordinates
} else {
obj[headers[j]] = currentline[j];
}
}
result.push(obj);
}
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}
如果是用于node.js的,我建议研究一下NPM软件包: csvtojson