Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highcharts how to use JavaScript variable as series data source?

I am running an asp.net code-behind that creates a string variable which holds a collection of floats separated by commas. Something like this in C#

string myCString = "4.5, 3.1, 6.5, 7.0, -1.3";

This variable then makes it into the an asp.net web page where it is assigned to a JavaScript variable:

var myJString = '<%=myCString %>';

Now we enter Highcharts where the syntax for a normal series looks like this:

series: [{
     name: 'Series1',
     data: [1.1, 3.8, 5.3, 9.8, 5.0]
       }]

What I would like to do is assign myJString to the data field of the series. I have tried two approaches and both did not work. The solution is probably trivial but I am far from even being an enthusiast programmer. It looks like the core of the problem is that Highcharts expects an array of numbers rather than a string. However, my understanding of the square brackets in JavaScript was that they convert whatever is within to a string?

Here is what did NOT work:

series: [{
     name: 'Series1',
     data: myJString    // does not work
       }]

series: [{
     name: 'Series1',
     data: myJString - 0    // does not work either
       }]

The second try was from highcharts - variable data causes browser lockup in retrospect it makes sense that it didn't work since subtracting 0 from a string that is not just a number falls short of the goal.

It also makes sense that the first try didn't work since it seems to want an array of numbers rather than a string. Now to my actual question(s):

Can I inexpensively convert my string of comma separated floats in JavaScript so I can use it in the data field, and if so, how do I do that? Would it be better (performance wise) to do this in the code-behind and pass an array to JavaScript and then try the whole thing with an array? This is assuming that the myJString not being an array of floats is the actual problem.

Thanks in advance for any insight you may be able to provide.

like image 410
Reality Extractor Avatar asked Apr 22 '11 01:04

Reality Extractor


1 Answers

Try this:

data: JSON.parse("[" + myJString + "]")

Basically this formats the string's contents as a JSON array. The parse function then de-serializes the string into a JavaScript array.

like image 91
Justin Ethier Avatar answered Oct 30 '22 02:10

Justin Ethier