如何在GO结构中处理JSON中的日期字段

huangapple go评论108阅读模式
英文:

How to deal with date fields from JSON in a GO struct

问题

我有一个JSON内容,其中包含一些日期字段,如"resolutiondate"、"created"和"updated",如下所示:

{
"expand":"names,schema",
"startAt":0,
"maxResults":50,
"total":1,
"issues":[
{
"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
"id":"id",
"self":"https://url1",
"key":"key1",
"fields":{
"summary":"Summary-1",
"customfield_10406":null,
"resolutiondate":"2021-06-10T10:07:35.000+0000",
"created":"2021-06-10T10:05:24.000+0000",
"description":"Description-1",
...
...
...
}

我正在将此JSON数据解组为GO结构,并将数据保存在Excel表中。一切都按预期工作,唯一的问题是我在GO结构中将日期字段定义为字符串数据类型,如下所示:

Resolved string json:"resolutiondate,omitempty"
Created string json:"created,omitempty"

因此,保存在Excel文件中的最终数据如下所示:

如何在GO结构中处理JSON中的日期字段

但我想将它们保存为Excel表中的日期数据类型,并以用户定义的格式-mm/dd/yyyy保存。如何有效地使用Golang的time包来实现这一点?请帮忙。

注意:我将无法分享我的完整代码和完整的JSON文件。

英文:

I have a JSON content, with some date fields like "resolutiondate" and "created" and "updated" as shown below

  1. {
  2. "expand":"names,schema",
  3. "startAt":0,
  4. "maxResults":50,
  5. "total":1,
  6. "issues":[
  7. {
  8. "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
  9. "id":"id",
  10. "self":"https://url1",
  11. "key":"key1",
  12. "fields":{
  13. "summary":"Summary-1",
  14. "customfield_10406":null,
  15. "resolutiondate":"2021-06-10T10:07:35.000+0000",
  16. "created":"2021-06-10T10:05:24.000+0000",
  17. "description":"Description-1",
  18. ...
  19. ...
  20. ...
  21. }

I am unmarshalling this JSON data into GO struct and saving the data in a excel sheet. Everything works as expected, the only issue is I'm defining the date fields as string datatypes in my GO struct, as below:

  1. Resolved string `json:"resolutiondate,omitempty"`
  2. Created string `json:"created,omitempty"`

Hence the final data saved in the excel file looks like:

如何在GO结构中处理JSON中的日期字段

But I want to save them as date datatype in the excel sheet, in a user defined format-mm/dd/yyyy. How can I effectively use the time package of Golang to achieve this ? Please help.

NOTE: I will be unable to share my complete code and the full JSON file.

答案1

得分: 9

用于从自定义格式进行反序列化的代码需要创建time.Time的包装器并实现json.Unmarshaler接口。

  1. type CustomTime struct {
  2. time.Time
  3. }
  4. func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
  5. date, err := time.Parse("\"2006-01-02T15:04:05.000-0700\"", string(b))
  6. if err != nil {
  7. return err
  8. }
  9. t.Time = date
  10. return
  11. }

现在将你的时间字段指定为CustomTime

  1. Resolved CustomTime `json:"resolutiondate,omitempty"`
  2. Created CustomTime `json:"created,omitempty"`

关于写入Excel的实现,你需要提供更多信息。

但是这是一个示例解决方案:

  1. func (t *CustomTime) ExcelDate() string {
  2. return t.Format("01/02/2006")
  3. }
英文:

For unmarshaling from custom format you need to create time.Time wrapper and implement json.Unmarshaler interface.

  1. type CustomTime struct {
  2. time.Time
  3. }
  4. func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
  5. date, err := time.Parse(`"2006-01-02T15:04:05.000-0700"`, string(b))
  6. if err != nil {
  7. return err
  8. }
  9. t.Time = date
  10. return
  11. }

Now specify your time fields as CustomTime

  1. Resolved CustomTime `json:"resolutiondate,omitempty"`
  2. Created CustomTime `json:"created,omitempty"`

For writting into excel you need to provide more info about your implementation.

But example solution:

  1. func (t *CustomTime) ExcelDate() string {
  2. return t.Format("01/02/2006")
  3. }

答案2

得分: 2

你可以将字符串包装为自定义类型,并使其实现Unmarshaler接口:

  1. type Unmarshaler interface {
  2. UnmarshalJSON([]byte) error
  3. }

然后,将时间以JSON格式解析为time.Time类型,并使用自定义的日期格式mm/dd/yyyy进行格式化。

  1. type Date string
  2. func (d *Date) UnmarshalJSON(bytes []byte) error {
  3. dd, err := time.Parse("\"2006-01-02T15:04:05.000+0000\"", string(bytes))
  4. if err != nil {
  5. return err
  6. }
  7. *d = Date(dd.Format("01/02/2006"))
  8. return nil
  9. }

现在,你可以在Go结构体中使用以下代码:

  1. Created Date `json:"created,omitempty"`

然后进行解组。

你可以在这里运行示例代码。

英文:

What you can do is, wrap string as your own custom type, and make it implement the Unmarshaler interface:

  1. type Unmarshaler interface {
  2. UnmarshalJSON([]byte) error
  3. }

Then take time coming with JSON and parse it to time.Time and format with your custom layout mm/dd/yyyy.

  1. type Date string
  2. func (d *Date) UnmarshalJSON(bytes []byte) error {
  3. dd, err := time.Parse(`"2006-01-02T15:04:05.000+0000"`, string(bytes))
  4. if err != nil{
  5. return err
  6. }
  7. *d = Date(dd.Format("01/02/2006"))
  8. return nil
  9. }

Now you can use

  1. Created Date `json:"created,omitempty"`

inside your Go struct and unmarshal.

Run sample code here

huangapple
  • 本文由 发表于 2021年10月8日 21:42:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/69496826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定