Highcharts how to use a javascript variable as a series data source?

I am running asp.net code that creates a string variable that contains 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 turns it into an asp.net webpage, where it is assigned to a JavaScript variable:

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

Now we introduce Highcharts, where the syntax for a normal series is as follows:

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

I would like to assign myJString to the series data field. I tried two approaches and both of them did not work. The solution is probably trivial, but I'm far from even being an enthusiastic programmer. It seems that the essence of the problem is that Highcharts expects an array of numbers, not a string. However, my understanding of square brackets in JavaScript was that they convert everything inside the string?

Here is what works NOT :

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

The second attempt consisted of highcharts - the variable data makes the browser block in retrospect, it makes sense that this did not work, since subtracting 0 from a string that is not just a number does not match the purpose.

It also makes sense that the first attempt did not work, as it seems that an array of numbers is required, not a string. Now to my question (s):

Can I inexpensively convert my string of comma-separated floats to JavaScript so that I can use it in a data field, and if so, how to do it? Would it be better (in terms of performance) to do this in encoding and pass the array to JavaScript, and then try everything with the array? This suggests that myJString, which is not an array of floats, is a real problem.

Thanks in advance for any information you can provide.

+4
source share
3 answers

Try the following:

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

It basically formats the contents of the string as a JSON array. The parse function then de-serializes the string into a JavaScript array.

For it to work, you will need to enable json2.js .

+13
source

Since data is an array type, you can use arrays for values ​​of type

 myData = [4.5, 3.1, 6.5, 7.0, -1.3]; 
+5
source

another simple approach uses the JavaScript String.split () function in this way.

series: [{name: 'Series1', data: myJString.split (',')}]

If you are not sure if you have a space after the decimal point or not, use RegEx.

series: [{name: 'Series1', data: myJString.split (/, [\ d] * /)}]

0
source

All Articles