To convert a JSON string (or a byte slice containing JSON) to a Go struct, you can “use the json.Unmarshal() function from the encoding/json package.”
Go JSON to Struct
Here is the step-by-step guide to convert JSON to Struct in Go:
- Define the struct that matches the expected structure of the JSON data.
- Convert the JSON string to a byte slice (if it’s not already in that form).
- Use json.Unmarshal() function to decode the JSON into the struct.
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
That’s it!
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.