parsing time “\“\““ as “\“2006-01-02T15:04:05Z07:00\““: cannot parse “\““ as “2006“

在尝试将空字符串解析为'2006-01-02T15:04:05Z07:00'格式时,遇到错误。解决方案可能涉及处理或忽略解析错误。在某些情况下,即使忽略错误也能正常工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I encounter the below error when I want to parse such string to struct.
parsing time “”"" as ““2006-01-02T15:04:05Z07:00"”: cannot parse “”” as "2006"

package main

import (
	"fmt"
	"time"
	"encoding/json"
)

func main() {
	s :=`[
	{"name":"test1","expireAt":"2050-12-31T00:00:00Z"},
	{"name":"test2","expireAt":""}
	]`
	var result []struct{
		Name string
		ExpireAt time.Time 
	}
	err :=json.Unmarshal([]byte(s),&result)
	if err!=nil{
	  fmt.Println(err)
	}
	for _,v :=range result{
	fmt.Println(v.ExpireAt)
	}
}

Output:

parsing time "\"\"" as "\"2006-01-02T15:04:05Z07:00\"": cannot parse "\"" as "2006"
2050-12-31 00:00:00 +0000 UTC
0001-01-01 00:00:00 +0000 UTC

Solution:

package main

import (
	"fmt"
	"time"
	"encoding/json"
)
type MyTime time.Time

func (m *MyTime) UnmarshalJSON(data []byte) error {
	if string(data) == "null" || string(data) == `""` {
		return nil
	}
	return json.Unmarshal(data, (*time.Time)(m))
}

func main() {
	s :=`[
	{"name":"test1","expireAt":"2050-12-31T00:00:00Z"},
	{"name":"test2","expireAt":""}
	]`
	var result []struct{
		Name string
		ExpireAt MyTime 
	}
	err :=json.Unmarshal([]byte(s),&result)
	if err!=nil{
	  fmt.Println(err)
	}
	for _,v :=range result{
	fmt.Println(time.Time(v.ExpireAt))
	}
}

Output:

2050-12-31 00:00:00 +0000 UTC
0001-01-01 00:00:00 +0000 UTC

BTW, there is one more point that I hope to get you guy’s attention. The point is that it can work fine if we ignore the error when we unmarshal the string to the struct.
For example:

package main

import (
	"encoding/json"
	"fmt"
	"time"
)

func main() {
	s := `[
	{"name":"test1","expireAt":"2050-12-31T00:00:00Z"},
	{"name":"test2"}
	]`
	var result []struct {
		Name     string
		ExpireAt time.Time
	}
	_ = json.Unmarshal([]byte(s), &result)
	for _, v := range result {
		fmt.Println(v.ExpireAt)
	}
}

Output

2050-12-31 00:00:00 +0000 UTC
0001-01-01 00:00:00 +0000 UTC
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值