how to convert json to struct in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert json to struct in golang, use json.Unmarshal(), it will convert json string to struct. You have to only pass your json in json.Unmarshal().


Related Tutorials

Golang JSON to string

Golang JSON to XML

Golang JSON to Map

Golang JSON to Struct


Today, I will show you how do I convert a json string to struct in golang, as above mentioned I’m going to use json.Unmarshal() with byte method.

Let’s start our Golang convert json to struct example

main.go

package main
  
import (
    "encoding/json"
    "fmt"
)

type Domain struct {
    Id        int
    Name      string
}
  
// main function
func main() {
  
    var domain Domain
  
    Data := []byte(`{
        "Id": 1,  
        "Name": "Infinitbility"
    }`)
  
    err := json.Unmarshal(Data, &domain)
  
    if err != nil {
        fmt.Println(err)
    }
  
    // printing details of
    // decoded data
    fmt.Println("Struct is:", domain)
    fmt.Println("Name is:", domain.Name)
}

In the above example, we have converted the json value to a struct and printed in golang console. let’s check the output.

Output

Struct is: {1 Infinitbility}
Name is: Infinitbility

I hope it helps you, All the best 👍.

Try it Yourself

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts