Reputation: 5790
i am creating highcharts (stacked column) ref http://www.highcharts.com/demo/column-stacked/gray
which requires it data to be display in a format like
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
But i have same in HTML Table
John Jane Joe
5 2 3
3 2 4
4 3 4
7 2 2
2 1 5
By using c# code behind i am able to convert HTML Table to string
string sHTMLTable = "John,5,3,4,7,2|Jane,2,2,3,2,1|Joe,3,4,4,2,5";
How can i convert same string in HighCharts required Array format ?
Upvotes: 0
Views: 692
Reputation: 15630
Sagar,
Please specify which language you are using.
Assuming that you are using C#
public class Employee
{
public string Name { get; set; }
public List<String> Data {get;set}
}
Adding some instances of them to a List:
List<String> abc=new List<String>()
abc.Add("1");
abc.Add("2");
abc.Add("3");
Employee oEmployee1 =
new Employee{Name="Joe",data=abc};
Employee oEmployee2 =
new Employee { Name = "Jane",data=abc};
Employee oEmployee3 =
new Employee { Name = "Joe", data=abc};
List<Employee> oList = new List<Employee>()
{ oEmployee1, oEmployee2, oEmployee3 };
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
This will generates the data in JSON format and you don't want to write any code to convert data to JSON.
Upvotes: 1
Reputation:
Split the string on the |
character, then use .map()
on the resulting Array to iterate the sub-strings.
Inside the .map()
callback, split the sub-string on the ,
character, and return an object with the first item as the name
property, and the remainder as the data
property.
var res = sHTMLTable.split("|").map(function(s) {
var arr = s.split(",");
return {name:arr.shift(), data:arr.map(Number)};
});
Notice that I used .map()
again when setting the data
. This was to convert the numeric strings to actual numbers.
Upvotes: 4
Reputation: 337580
Assuming you can get your sHTMLTable
variable from C# to the javascript of the rendered page (either via a hidden field or response.writing it inside a <script>
tag) this should work:
var sHTMLTable = "John,5,3,4,7,2|Jane,2,2,3,2,1|Joe,3,4,4,2,5";
var aPersonData = sHTMLTable.split('|');
var series = [];
for (var i = 0; i < aPersonData.length; i++) {
var data = aPersonData[i].split(',');
var obj = {
name: data.shift(),
data: data
};
series.push(obj);
};
Upvotes: 2