Json decoder: how to unmarshal data with go

How to decode a JSON string to a golang object using the build in encoding/json golang module. You will see how to define a custom golang struct, how to define the json string data as a []byte and how to unmarshal the json string and put the data in the custom golang struct. You will also see how to do the error handling to be sure the json data is a valid one. Json is a string representation of an object, it contains string, number or boolean information of the data. If you are interested in data marshaling and converting the golang struct to the json data, you can check this in this tutorial.

Code

err := json.Unmarshal([]byte data, &struct by reference)

Example golang json to struct

In this example we have a very simple json struct, defined by an object that contains a title and a description, both string. We will start from the json string defined and parse the json into a golang struct, called Data in the example. Using the json attribute for each struct key, you will map the data to the right json key name, in this case we have to differenciate betwenn uppercase and lowercase. Finally we will use the golang json unmarshal functionality, to map the json string data, to the json struct.

package main

import (
	"encoding/json"
	"fmt"
)

type Data struct {
	Title       string `json:"title"`
	Description string `json:"description"`
}

func main() {
	dataJson := []byte(`{"title":"your title","description":"description"}`)

	var data Data
	if err := json.Unmarshal(dataJson, &data); err == nil {
		fmt.Println(data)
	} else {
		panic(err)
	}
}

How to unmarshal an undefined json struct to a golang interface

If you are not sure about the json data structure, you can map everything to a generic golang interface object.

	dataJson := []byte(`{"title":"your title","description":"description"}`)

	var data interface{}
	if err := json.Unmarshal(dataJson, &data); err == nil {
		if dataInterface, ok := data.(map[string]interface{}); ok {
			if dataTitle, ok := dataInterface["title"].(string); ok {
				fmt.Println(dataTitle)
			}
		}
	} else {
		panic(err)
	}

Let's define the generic interface data interface with var data interface{}

You can unmarshal your data directly to a golang interface struct.

In this case, you will have to cast and check every single variable, if you are not sure about the data structure.

You can cast a variable in this way: variable.(casting type)

 

Other articles