我编写了一个使用d3.js读取csv文件的代码。我的csv文件是
x1,y1,x2,y2
2.0000,0.0000,-4.0000,1.5000
1.9800,0.0000,-3.9500,1.5000
1.9600,0.0000,-3.9000,1.5000
1.9400,0.0000,-3.8500,1.5000
1.9200,0.0000,-3.8000,1.5000
我读取此文件的代码是
d3.csv("./data.csv", function(err, data){
data1 = data.map(function(d) { return [ +d["x1"], +d["y1"] ]; });
data2 = data.map(function(d) { return [ +d["x2"], +d["y2"] ]; });})
此代码读取csv文件并将其数据保存到数组,data1和data2中。
每个数组看起来像
data1 [0] [0] = 2.0000,data1 [0] [1] = 0.0000
data1 [1] [0] = 1.9800,data1 [1] [1] = 0.0000
data1 [2] [0] = 1.9600,data1 [2] [1] = 0.0000
现在,我想通过阅读json数据做同样的事情。 我的json代码是
var inputdata = [
{"y2": "1.5000", "x2": "-4.0000","y1": "0.0000", "x1": "2.0000"},
{"y2": "1.5000", "x2": "-3.9500","y1": "0.0000", "x1": "1.9800"},
{"y2": "1.5000", "x2": "-3.9000","y1": "0.0000", "x1": "1.9600"},
{"y2": "1.5000", "x2": "-3.8500","y1": "0.0000", "x1": "1.9400"},
{"y2": "1.5000", "x2": "-3.8000","y1": "0.0000", "x1": "1.9200"},
];
然后我如何读取这个json代码并将数据放入数组data1和data2,如上面的csv代码?
答案 0 :(得分:0)
您可以这样做:
var inputdata = [
{"y2": "1.5000", "x2": "-4.0000","y1": "0.0000", "x1": "2.0000"},
{"y2": "1.5000", "x2": "-3.9500","y1": "0.0000", "x1": "1.9800"},
{"y2": "1.5000", "x2": "-3.9000","y1": "0.0000", "x1": "1.9600"},
{"y2": "1.5000", "x2": "-3.8500","y1": "0.0000", "x1": "1.9400"},
{"y2": "1.5000", "x2": "-3.8000","y1": "0.0000", "x1": "1.9200"},
];
data1 = inputdata.map(function(d) { return [ +d["x1"], +d["y1"] ]; });
data2 = inputdata.map(function(d) { return [ +d["x2"], +d["y2"] ]; });
//do your task with data1 and data2