问题已更新
谢谢大家回答我上次提出的不成熟的问题,但是,我仍然无法弄清楚如何处理[x,y]系列数据。
当数据是单个整数数组时,它工作正常,但是struct数组不起作用。我该如何解决?
series: [{//should work like this
data: [
["1", 29.9],
["2", 71.5],
["3", 106.4]
]
}]
type Line struct {//my struct
Data []Point `json:"data"` //this is the tricky part
}
type Point struct {
Date string
Value int
}
<script>
$(document).ready(function() {
var options = {
chart: {
renderTo: 'ERP_Chart',
type: 'spline'
},
series: []
};
$.getJSON("/Get_ERP_Chart", function(data) {
options.series = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
我的服务器端Go代码
type Line struct {
Data []Point `json:"data"` //this is the tricky part...
}
type Point struct {
Date string
Value int
}
func showERPChart(writer http.ResponseWriter, request *http.Request) {
var profit, expense, contacts Line
var chart []Line
rows, err := Db.Query("SELECT profit,expense,contacts,_date FROM Sells ORDER BY _date")
var prof, exp, con int
var date string
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)
js, _:= json.Marshal(chart)
writer.Write(js)
}
答案 0 :(得分:1)
要让encoding/json以您希望的方式工作,您需要export您的结构字段。
来自encoding/json
文档:
Struct值编码为JSON对象。每个导出结构字段 使用字段名称作为对象成为对象的成员 密钥,除非出于以下原因之一省略该字段。
解码相同:
Unmarshal只会设置结构的导出字段。