How to convert a JSON to a Struct in Go

#go

Last updated on Jun 19, 2021 by Suraj Sharma



In this tutorial, you will learn to convert a known JSON string to a Go struct using the package json by importing encoding/json

import "encoding/json"


To convert a known JSON string to a struct data type we use the UnMarshal function


Example

package main

import (
    "encoding/json"
    "fmt"
)

type Post struct {
    ID uint        `json:"id"`
    Title string   `json:"title"`
    Author string  `json:"author"`
    Content string `json:"content"`
}
func main () {
    // create an instance of Post struct
    post := Post{}

    // convert a JSON string to a []byte first
    b := []byte(`{"id":1,"title":"Go Tutorial","author":"Suraj Sharma","content":"Learn Golang by examples"}`)

    // use json.UnMarshal to convert the []byte of JSON data to struct
    // by passing pointer to post variable as a second argument

    err := json.Unmarshal(b, &post)

    if err != nil {
        fmt.Println("Unable to convert the JSON string to a struct")
    } else {
        // print the post
        fmt.Println(post)
    }
}
// Output
// {1 Go Tutorial Suraj Sharma Learn Golang by examples}


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.