How to efficiently convert JSON strings to time.Duration in Go?
Efficiently handle the conversion of JSON strings to time.Duration
in Go language to avoid errors caused by direct deserialization. This article provides a simple and efficient solution.
Problem background: When deserializing JSON using encoding/json
package, converting the JSON string directly to time.Duration
type will cause an error.
Solution: Replace the time.Duration
field with int64
. Since the underlying type of time.Duration
is int64
, this method can directly store the length of time represented by the JSON string. After deserialization, use the time.ParseDuration()
function to convert it to time.Duration
type.
Code example:
package main import ( "encoding/json" "fmt" "time" ) type Student struct { Id int `json:"id"` Gender string `json:"gender"` Name string `json:"name"` Sno string `json:"sno"` Tim int64 `json:"time"` // Use int64 to store time length} func main() { jsonData := []byte(`{"id":12,"gender":"Male","name":"Li Si","sno":"001","time":2000}`) // 2s = 2000ms var s1 Student json.Unmarshal(jsonData, &s1) duration, err := time.ParseDuration(fmt.Sprintf("%dms", s1.Tim)) if err != nil { fmt.Println("Error parsing duration:", err) } else { fmt.Printf("Duration: %v\n", duration) } }
Other methods, such as customizing structures and implementing the UnmarshalJSON
method, although feasible, increase the code complexity and ultimately require type conversion. This method is not as simple and efficient. Therefore, it is recommended to use int64
as the intermediate storage type and to perform explicit conversions when needed, which is a more direct and efficient solution.
The above is the detailed content of How to efficiently convert JSON strings to time.Duration in Go?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go's error interface is defined as typeerrorinterface{Error()string}, allowing any type that implements the Error() method to be considered an error. The steps for use are as follows: 1. Basically check and log errors, such as iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}. 2. Create a custom error type to provide more information, such as typeMyErrorstruct{MsgstringDetailstring}. 3. Use error wrappers (since Go1.13) to add context without losing the original error message,

Goisidealforbuildingscalablesystemsduetoitssimplicity,efficiency,andbuilt-inconcurrencysupport.1)Go'scleansyntaxandminimalisticdesignenhanceproductivityandreduceerrors.2)Itsgoroutinesandchannelsenableefficientconcurrentprogramming,distributingworkloa

Bitcoin’s price fluctuations today are affected by many factors such as macroeconomics, policies, and market sentiment. Investors need to pay attention to technical and fundamental analysis to make informed decisions.

The top ten digital currency exchanges such as Binance, OKX, gate.io have improved their systems, efficient diversified transactions and strict security measures.

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

The top ten cryptocurrency trading platforms in the world include Binance, OKX, Gate.io, Coinbase, Kraken, Huobi Global, Bitfinex, Bittrex, KuCoin and Poloniex, all of which provide a variety of trading methods and powerful security measures.

Goisastrongchoiceforprojectsneedingsimplicity,performance,andconcurrency,butitmaylackinadvancedfeaturesandecosystemmaturity.1)Go'ssyntaxissimpleandeasytolearn,leadingtofewerbugsandmoremaintainablecode,thoughitlacksfeatureslikemethodoverloading.2)Itpe
