This sample program demonstrates how to decode a JSON string.


Go language comes with more flexibility to work with the JSON document. In below example you can decode or unmarshal the JSON document into a map variable. The function Unmarshal of the json package is used to decode JSON values into Go values.

Example

package main

import (
	"fmt"	
	"encoding/json"	// Encoding and Decoding Package
)

// JSON Contains a sample String to unmarshal.

var JSON = `{
	"name":"Mark Taylor",
	"jobtitle":"Software Developer",
	"phone":{
		"home":"123-466-799",
		"office":"564-987-654"
	},
	"email":"markt@gmail.com"
}`

func main() {
	// Unmarshal the JSON string into info map variable.
	var info map[string]interface{}
	json.Unmarshal([]byte(JSON),&info)

	// Print the output from info map.
	fmt.Println(info["name"])
	fmt.Println(info["jobtitle"])
	fmt.Println(info["email"])
	fmt.Println(info["phone"].(map[string]interface{})["home"])	
	fmt.Println(info["phone"].(map[string]interface{})["office"])
}

Output

Mark Taylor
Software Developer
markt@gmail.com
123-466-799
564-987-654
Here is the syntax for Unmarshal functions in Go:
func Unmarshal(data []byte, variable interface{}) error

The function Unmarshal parses the JSON-encoded data and stores the result into the second argument ( variable interface{} ).
The map variable "info" is declared as a map with a key of type string and a value of type interface{}.
This means the map can store any type of value for any given key.

Most Helpful This Week