0

Question Updated

Thank you all for answering my immature question asked last time, however, I still cannot figure out how to handle the [x,y] series data.

It works fine when Data is a single array of integers, but an array of struct doesn't work. How can I solve it?

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>

My server-side Go code

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)
}
Robert Tao
  • 21
  • 3

1 Answers1

1

For encoding/json to work the way you want to, you need to export your struct fields.

From encoding/json docs:

Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.

Same for decoding:

Unmarshal will only set exported fields of the struct.

mkopriva
  • 35,176
  • 4
  • 57
  • 71