Go:javascript的格式结构(不带键的json)

I have to form a slice of structs for the chart. Marshal it, and return to the frontend widget. Widget is waiting for the format like this :

[["1455523840380",1],["1455523840383",2],["1455523840384",3]]

But My data comes like this :

[{"Time":1.45552462158e+12,"Value":1},{"Time":1.45552462158e+12,"Value2},{"Time":1.45552462158e+12,"Value3}]

My struct that is coming to the slice is made like this :

type ChartElement struct {
    Time  int `json:""`
    Value int `json:""`
}

I have now 2 main troubles:

  1. how to make the json without keys, but just 2 values with comma between them?
  2. how to convert date or time to the javascript miliseconds correctly?

The output format you want:

[["1455523840380",1],["1455523840383",2],["1455523840384",3]]

In JSON it is not an array of struct, but an array of arrays.

Since the "internal" array has various types (string and numeric), you can model it like this:

type ChartElement []interface{}

And you can populate it like this:

s := []ChartElement{{"1455523840380", 1}, {"1455523840383", 2}, {"1455523840384", 3}}

And if you marshal it to JSON:

data, err := json.Marshal(s)
fmt.Println(string(data), err)

Output is what you expect:

[["1455523840380",1],["1455523840383",2],["1455523840384",3]] <nil>

And the time values such as 1455523840380 are the the number of milliseconds elapsed since January 1, 1970 UTC. In Go you can get this value from a time.Time value with its Time.UnixNano() method and dividing it by 1000000 (to get milliseconds from nanoseconds), for example:

fmt.Println(time.Now().UnixNano() / 1000000) // Output: 1455526958178

Note that in order to have time values as strings in the JSON output, you have to add these time values as strings in the []ChartElement. To convert this millisecond value to string, you can use strconv.FormatInt(), e.g.

t := time.Now().UnixNano() / 1000000
timestr := strconv.FormatInt(t, 10) // timestr is of type string