Home Backend Development Golang How to efficiently convert JSON strings to time.Duration in Go?

How to efficiently convert JSON strings to time.Duration in Go?

Apr 02, 2025 pm 02:51 PM
go language ai

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)
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Understanding Go's error Interface Understanding Go's error Interface Apr 27, 2025 am 12:16 AM

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,

Building Scalable Systems with the Go Programming Language Building Scalable Systems with the Go Programming Language Apr 25, 2025 am 12:19 AM

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

Bitcoin price today Bitcoin price today Apr 28, 2025 pm 07:39 PM

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.

What are the top ten virtual currency trading apps? The latest digital currency exchange rankings What are the top ten virtual currency trading apps? The latest digital currency exchange rankings Apr 28, 2025 pm 08:03 PM

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

The Execution Order of init Functions in Go Packages The Execution Order of init Functions in Go Packages Apr 25, 2025 am 12:14 AM

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations

Go in Production: Real-World Use Cases and Examples Go in Production: Real-World Use Cases and Examples Apr 26, 2025 am 12:18 AM

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

Which of the top ten currency trading platforms in the world are the latest version of the top ten currency trading platforms Which of the top ten currency trading platforms in the world are the latest version of the top ten currency trading platforms Apr 28, 2025 pm 08:09 PM

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.

Go vs. Other Languages: A Comparative Analysis Go vs. Other Languages: A Comparative Analysis Apr 28, 2025 am 12:17 AM

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

See all articles