由golang编写的Highcharts数据[x,y]

时间:2017-04-27 11:04:29

标签: json go highcharts

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

当Data是一个整数的数组时,它工作正常,但一个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)
}

1 个答案:

答案 0 :(得分:1)

您需要为Point实施custom marshaller。以下是一个示例实现:

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运行示例。