How to convert a JSON to a Struct in Golang

Last updated on Jun 19, 2021 by Suraj Sharma



In this tutorial, you will learn to convert a known JSON string to a Golang 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":"Golang 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 Golang Tutorial Suraj Sharma Learn Golang by examples}


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.