douming4359 2016-02-15 08:29
浏览 24
已采纳

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?
  • 写回答

1条回答 默认 最新

  • douhuai2861 2016-02-15 08:57
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等