Highcharts data [x,y] written by golang



我正在使用GO将数据写入HighCharts,但我无法弄清楚如何处理系列数据[x,y]

当数据是一个整数数组时,它可以正常工作,但是 struct的数组不起作用,这很大程度上是因为它不是正确的格式。我该如何解决?

它应该像这样的jsfiddle工作,使用字符串作为x工作,对我来说很好。

series: [{//should work like this
    name:"whatever",
    data: [
    ["1999/12/12", 29.9],
    ["1999/12/13", 71.5],
    ["1999/12/14", 106.4]
    ]
}]
type Line struct {//my struct, Data is not in the correct format...
Name string  `json:"name"`
Data []Point `json:"data"`  //this is the tricky part
}
type Point struct {
Date  string
Value int
}

脚本:

<script>
$(document).ready(function() {
    var options = {
        chart: {
        zoomType: 'x',
        renderTo: 'ERP_Chart',
        type: 'line'
        },
        title: {
        text: 'ERP Chart'
        },
        series: [{}]
};
$.getJSON("/Get_ERP_Chart", function(data) {
    options.series = data;
    var chart = new Highcharts.Chart(options);
    });
});
</script>

golang代码:

type Line struct {
Name string  `json:"name"`
Data []Point `json:"data"`
}
type Point struct {
Date  string
Value int
}
func showERPChart(writer http.ResponseWriter, request *http.Request) {
var profit, expense, contacts Line
var chart []Line //chart contains multiple series of line.
//The code below is just getting data, don't focus on it
rows, err := Db.Query("SELECT profit,expense,contacts,_date FROM Sells ORDER BY _date")
var prof, exp, con int
var date string
profit.Name = "profit"
expense.Name = "expense"
contacts.Name = "contacts"
for rows.Next() {
    err = rows.Scan(&prof, &exp, &con, &date)
    profit.Data = append(profit.Data, Point{date, prof})
    expense.Data = append(expense.Data, Point{date, exp})
    contacts.Data = append(contacts.Data, Point{date, con})
}
chart = append(chart, profit)
chart = append(chart, expense)
chart = append(chart, contacts)
//done reading data
js, err := json.Marshal(chart)
writer.Write(js)
}

您需要为Point实现自定义邮政服务器。以下是实现的示例:

func (p *Point) MarshalJSON() ([]byte, error) {
    var buf bytes.Buffer
    buf.WriteString(`["`)
    buf.WriteString(p.Date)
    buf.WriteString(`",`)
    buf.WriteString(strconv.Itoa(p.Value))
    buf.WriteRune(']')
    return buf.Bytes(), nil
}

在Go Playground上运行示例。

最新更新