简体   繁体   English

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

[英]Go : format struct for javascript (json without keys)

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? 如何使json没有键,但只有2个值,且它们之间有逗号?
  2. how to convert date or time to the javascript miliseconds correctly? 如何将日期或时间正确转换为javascript毫秒?

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. 在JSON中,它不是结构数组,而是数组数组。

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: 如果将其封送为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. 时间值(例如1455523840380是自1970年1月1日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: 在围棋,你可以从一个得到这个值time.Time其价值Time.UnixNano()方法,然后除以1000000 (摆脱纳秒毫秒),例如:

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 string s in the []ChartElement . 请注意,为了使时间值在JSON输出中作为字符串,您必须在[]ChartElement中将这些时间值作为string s添加。 To convert this millisecond value to string , you can use strconv.FormatInt() , eg 要将毫秒值转换为string ,可以使用strconv.FormatInt() ,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM