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

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

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

{
   "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",
            ...
            ...
            ...
}

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:

		Resolved           string `json:"resolutiondate,omitempty"`
		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接口。

type CustomTime struct {
    time.Time
}

func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
    date, err := time.Parse("\"2006-01-02T15:04:05.000-0700\"", string(b))
    if err != nil {
        return err
    }
    t.Time = date
    return
}

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

Resolved           CustomTime `json:"resolutiondate,omitempty"`
Created            CustomTime `json:"created,omitempty"`

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

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

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

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

type CustomTime struct {
	time.Time
}

func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
	date, err := time.Parse(`"2006-01-02T15:04:05.000-0700"`, string(b))
	if err != nil {
		return err
	}
	t.Time = date
	return
}

Now specify your time fields as CustomTime

Resolved           CustomTime `json:"resolutiondate,omitempty"`
Created            CustomTime `json:"created,omitempty"`

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

But example solution:

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

答案2

得分: 2

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

type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}

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

type Date string

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

	return nil
}

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

Created Date `json:"created,omitempty"`

然后进行解组。

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

英文:

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

type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}

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

type Date string

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

	return nil
}

Now you can use

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:

确定