SoFunction
Updated on 2025-03-01

Use of the JSON decoding function Unmarshal in Golang language

Preface

We often encounter data decoding JSON format at work. This article introduces the four JSON formats commonly used in work through 4 examples. In Golang language, the function Unmarshal in the encoding/json package of the standard library is usually used to decode JSON format data. Let's first introduce how to use this function, and then use 4 sample codes to demonstrate how to decode the common 4 JSON format data in Golang.

func Unmarshal

func Unmarshal(data []byte, v interface{}) error

The Unmarshal function parses json-encoded data and stores the result into the value pointed to by v.

Unmarshal and Marshal do the opposite operation, and apply for mapping, slice or pointer if necessary, with the following additional rules:

To write json data decoding into a pointer, the Unmarshal function first handles the case where the json data is json literal null. At this time, the function sets the pointer to nil; otherwise, the function decodes the json data and writes the value pointed to by the pointer; if the pointer itself is nil, the function will first apply for a value and make the pointer point to it.

To write json data decoding to a struct, the function matches the key of the input object and the key used by Marshal (the key name specified by the struct field name or its label), preferentially selects an exact match, but also accepts case-insensitive matches.

To decode json data to write an interface type value, the function will decode the data to the following types to write to the interface:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

If a JSON value does not match the given target type, or if a json number overflows when writing to the target type, the Unmarshal function will skip the field and try to complete the rest of the decoding operations. If no more serious error occurs, this function returns an UnmarshalTypeError describing the details of the first such error.

When decoding the null value of JSON to go's interface, pointer, and slice, they will be set to nil, because null generally means "not existed" in json. When decoding json's null value to other go types, there will be no changes or errors.

When decoding a string, an illegal utf-8 or utf-16 proxy (character) pair is not considered an error, but instead an illegal character is replaced with a unicode character U+FFFD.

Normal JSON

Sample code:

package main

import (
   "encoding/json"
   "fmt"
)

// Actress actresstype Actress struct {
   Name       string
   Birthday   string
   BirthPlace string
   Opus       []string
}

func main() {

   // Ordinary JSON   // Because the parameters received by the() function are byte slices, // So the JSON string needs to be converted into byte slices.  jsonData := []byte(`{      "name":"Dilraba Dilraba",
      "birthday":"1992-06-03",
      "birthPlace":"Urumqi City, *",
      "opus":[
         "Anaerhan",
         "Backlight Love",
         "Cara Lovers"
      ]
   }`)

   var actress Actress
   err := (jsonData, &actress)
   if err != nil {
      ("error:", err)
      return
   }
   ("Name: %s\n", )
   ("Birthday: %s\n", )
   ("Site of Birth: %s\n", )
   ("work:")
   for _, val := range  {
      ("\t", val)
   }
}

Running results:

Name: Di Lieba

Birthday: 1992-06-03

Place of birth: Urumqi, *

work:

"Anaerhan"

"Backlight Love"

"Cara Lovers"

JSON embedded normal JSON

Sample code:

package main

import (
   "encoding/json"
   "fmt"
)
// Opus workstype Opus struct {
   Date string
   Title string
}
// Actress actresstype Actress struct {
   Name       string
   Birthday   string
   BirthPlace string
   Opus       Opus
}

func main () {
   // JSON nesting normal JSON   jsonData := []byte(`{
      "name":"Dilraba Dilraba",
      "birthday":"1992-06-03",
      "birthPlace":"Urumqi City, *",
      "opus": {
         "Date":"2013",
         "Title":"Anaerhan"
      }
   }`)
   var actress Actress
   err := (jsonData, &actress)
   if err != nil {
      ("error:", err)
      return
   }
   ("Name: %s\n", )
   ("Birthday: %s\n", )
   ("Site of Birth: %s\n", )
   ("work:")
("\t%s:%s", ,   )}

Running results:

Name: Di Lieba

Birthday: 1992-06-03

Place of birth: Urumqi, *

work:

2013: "Anaerhan"

JSON embedded array JSON

Sample code:

package main

import (
   "encoding/json"
   "fmt"
)

type Opus struct {
   Date string
   Title string
}
type Actress struct {
   Name string
   Birthday string
   BirthPlace string
   Opus []Opus
}

func main () {
   // JSON nested array JSON   jsonData := []byte(`{
      "name":"Dilraba Dilraba",
      "birthday":"1992-06-03",
      "birthPlace":"Urumqi City, *",
      "opus":[
         {
            "date":"2013",
            "title":"Anaerhan"
         },
         {
            "date":"2014",
            "title":"Backlight Love"
         },
         {
            "date":"2015",
            "title":"Cara Lovers"
         }
      ]
   }`)
   var actress Actress
   err := (jsonData, &actress)
   if err != nil {
      ("error:", err)
      return
   }
   ("Name: %s\n", )
   ("Birthday: %s\n", )
   ("Site of Birth: %s\n", )
   ("work:")
   for _, val := range  {
      ("\t%s - %s\n", , )
   }
}

Running results:

Name: Di Lieba

Birthday: 1992-06-03

Place of birth: Urumqi, *

work:

2013 - "Anaerhan"

2014 - "Backlight Love"

2015 - "Cara Lovers"

JSON embedded with dynamic key

Sample code:

package main

import (
   "encoding/json"
   "fmt"
)

// Opus workstype Opus struct {
   Type string
   Title string
}
// Actress actresstype Actress struct {
   Name string
   Birthday string
   BirthPlace string
   Opus map[string]Opus
}

func main () {
   jsonData := []byte(`{
      "name":"Dilraba Dilraba",
      "birthday":"1992-06-03",
      "birthPlace":"Urumqi City, *",
      "opus":{
         "2013":{
            "Type":"Modern Revolutionary Drama",
            "Title":"Anaerhan"
         },
         "2014":{
            "Type":"Fantasy Drama",
            "Title":"Backlight Love"
         },
         "2015":{
            "Type":"Love Drama",
            "Title":"Cara Lovers"
         }
      }
   }`)
   var actress Actress
   err := (jsonData, &actress)
   if err != nil {
      ("error:", err)
      return
   }
   ("Name: %s\n", )
   ("Birthday: %s\n", )
   ("Site of Birth: %s\n", )
   ("work:")
   for index, value := range  {
      ("\tDate: %s\n", index)
      ("\t\tCategory: %s\n", )
      ("\t\tTitle: %s\n", )
   }
}

Running results:

Name: Di Lieba

Birthday: 1992-06-03

Place of birth: Urumqi, *

work:

Date: 2013

Category: Modern Revolutionary Dramas

Title: "Anaerhan"

Date: 2014

Category: Fantasy drama

Title: "Backlight Love"

Date: 2015

Category: Romance Drama

Title: "Cara Lovers"

Summarize

We first introduced the Unmarshal function in the encoding/json package of the Golang standard library, and then through the above 4 sample codes, we introduced how to decode the following four JSON format data:

JSON format 1:

{
    "name":"Dilraba Dilraba",
    "birthday":"1992-06-03",
    "birthPlace":"Urumqi City, *",
    "opus":[
        "Anaerhan",
        "Backlight Love",
        "Cara Lovers"
    ]
}

JSON format 2:

{
    "name":"Dilraba Dilraba",
    "birthday":"1992-06-03",
    "birthPlace":"Urumqi City, *",
    "opus":{
        "Date":"2013",
        "Title":"Anaerhan"
    }
}

JSON format 3:

{
    "name":"Dilraba Dilraba",
    "birthday":"1992-06-03",
    "birthPlace":"Urumqi City, *",
    "opus":[
        {
            "date":"2013",
            "title":"Anaerhan"
        },
        {
            "date":"2014",
            "title":"Backlight Love"
        },
        {
            "date":"2015",
            "title":"Cara Lovers"
        }
    ]
}

JSON format 4:

{
    "name":"Dilraba Dilraba",
    "birthday":"1992-06-03",
    "birthPlace":"Urumqi City, *",
    "opus":{
        "2013":{
            "Type":"Modern Revolutionary Drama",
            "Title":"Anaerhan"
        },
        "2014":{
            "Type":"Fantasy Drama",
            "Title":"Backlight Love"
        },
        "2015":{
            "Type":"Love Drama",
            "Title":"Cara Lovers"
        }
    }
}

This is the end of this article about the use of the Golang language JSON decoding function Unmarshal. For more information about Golang JSON Unmarshal, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!