Parsing JSON with golang

Golang supports an API that handles JSON using encoding/json package. we use unmarshal function for decoding a JSON string.

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

)

func  main()  {
	fmt.Println("---- json to struct ------")
	type User struct {
		UserId int json:"userId"
		Id int json:"id"
		Title string json:"title"
		Completed bool json:"completed"
	}
	var user User
	str := {"userId":1,"id":1,"title":"delectus aut autem","completed":false}
	err := json.Unmarshal([]byte(str), & user)
	if err != nil {
        fmt.Println(err)
        }
	fmt.Println("userId :- ",user.UserId)
	fmt.Println("Id :- ",user.Id)
	fmt.Println("Title :- ",user.Title)
	fmt.Println("Completed :- ",user.Completed)
}

Output

Conclusion

Finally, we parsed the json in go; stay tuned for more go tutorials.

Leave a Comment