将CSV转换为JSON时遇到困难.Below是我要转换的代码
d3.csv("http://localhost:8080/Sample/flight.csv", function(flights) {
//alert(flights);
var linksByOrigin = {},
countByAirport = {},
locationByAirport = {},
positions = [];
var arc = d3.geo.greatArc()
.source(function(d) { return locationByAirport[d.source]; })
.target(function(d) { return locationByAirport[d.target]; });
//reading from csv
flights.forEach(function(flight) {
var origin = flight.origin,
destination = flight.destination,
links = linksByOrigin[origin] || (linksByOrigin[origin] = []);
links.push({source: origin, target: destination});
countByAirport[origin] = (countByAirport[origin] || 0) + 1;
countByAirport[destination] = (countByAirport[destination] || 0) + 1;
});
});
到
d3.json("http://localhost:8080/Sample/flight.json", function(flights) {
//alert(flights);
var linksByOrigin = {},
countByAirport = {},
locationByAirport = {},
positions = [];
var arc = d3.geo.greatArc()
.source(function(d) { return locationByAirport[d.source]; })
.target(function(d) { return locationByAirport[d.target]; });
var flights = flights.flights;
alert("flights"+flights.length);
for(var i = 0; i < flights.length; i++) {
alert("origin"+flights[i].origin+"dest"+flights[i].destination);
var origin = flights[i].origin;
var destination = flights[i].destination;
alert("origin"+origin+"dest"+destination)
var links = linksByOrigin[origin] || (linksByOrigin[origin] = []);
links.push({source: origin , target: destination});
countByAirport[origin] = (countByAirport[origin] || 0) + 1;
countByAirport[destination] = (countByAirport[destination] || 0) + 1;
}
});
当我使用json代码时,它正在给我19:15:41.950 TypeError: _ is undefined1 d3.v2.js:1982:10
。
请告诉我在转换时我做错了什么。
答案 0 :(得分:0)
我需要查看你的json对象以获取更多信息,但基于以下假设,你的csv返回了一个对象数组:
[{origin: 'origin string', destination: 'destination string'} ... ]
如果您的json存储如下:
{flights: [{origin: 'origin string', destination: 'destination string'}, ...]}
那么你的代码应该可行。如果您的json格式不同,如果您可以上传示例csv和json文件,我可以给您更好的答案。
很难说这个错误有什么问题,但我的猜测是你没有在你的json文件中设置一个航班变量。