简体   繁体   中英

How can I parse csv data from a javascript array of strings for use in d3 graphs

I want to use data in a javascript array of strings to produce a d3 graph, to display a time series of timestamp(t), receive (rx), and transmit (tx) counters. Each member of the array is a string corresponding to one line of time,rx,tx (yes, with comma separators). I don't want to use d3.request based methods. I have already read the file from the server using server-side lua code and placed the data into the page using jslines.push(string).

109 // Show results so far
110 for (i=0; i < jslines.length; i++) {
111     console.log(i + ": " + jslines[i]);
112 }

The above section gives me confidence data is as I've described. For now I am just trying to pull out each of the 3 data values from a "line" and then repeat. I don't care that they'll still be strings at this point. Numbers later.

My reference for this is: https://github.com/d3/d3-dsv/blob/master/README.md#csvParseRows but I'm clearly misunderstanding the work needed.

114 var dataArray = d3.csvParseRows(jslines, function(d, i) {
115   return {
116     time: d[0],
117     rx:   d[1],
118     tx:   d[2]
119   };
120 });

Would be thankful for (kind) suggestions and/or a working example of using d3 to parse and prep data that d3 is not itself pulling from a remote (or local) file. Most of the examples I can find are asking d3 to pull the file content across to the client station, I believe.

Thanks ...Alan

If you already have the string, you can just split it like this:

var a = "1,2,3"
var b = a.split(",")
console.log(b[1])

Specifically, for your example, you can extract the data like this:

var data = jslines.map(function(l) {
  data = l.split(",");
  return({time: data[0], rx: data[1], tx: data[2]});
})

And then construct your d3 plot based on the resulting array of objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM