Skip to content

JSON Unmarshal Golang Example

You have a JSON in string and you want to map its values into a struct, take a look at this simple example:

package main

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

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

func main() {
	jsonBytes := []byte(`{"name": "Morteza", "age": 23}`)
	var user User

	err := json.Unmarshal(jsonBytes, &user)
	if err != nil {
		log.Fatalf("failed to marshal: %s", err)
	}

	fmt.Println(user.Name)
	fmt.Println(user.Age)
}

Leave a Reply

Your email address will not be published. Required fields are marked *