How to Convert JSON to Struct in Golang

To convert JSON to Struct in Golang, you can use the “json.Unmarshal()” function. The “json.Unmarshal()” function decodes JSON data and populates a struct with the corresponding values.

Example

package main

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

type Person struct {
  Name string `json:"name"`
  Age int `json:"age"`
}

func main() {
  jsonData := []byte(`{"name":"Krunal Lathiya","age":30}`)

  var person Person

  err := json.Unmarshal(jsonData, &person)
  if err != nil {
    log.Fatal(err)
  }

  fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)
}

Output

Name: Krunal Lathiya, Age: 30

In this example, we defined a Person struct with two fields: Name and Age.

The json struct tags specify the JSON field names that should be mapped to the corresponding struct fields.

In the next step, we created a byte slice jsonData containing the JSON data to be decoded.

Next, we created a person variable and used the “json.Unmarshal()” function to decode the JSON data and populate the person struct.

If there is an error during the decoding process, the program will log the error and exit.

Finally, we printed the values of the person struct.

Leave a Comment