JSON Unmarshal interface values in Go

Sai
2 min readJul 5, 2022

Unmarshalling is also known as deserializing. It is the process of converting the byte stream to original data.

Unmarshal function Syntax:

func Unmarshal(data []byte, v any) error

Unmarshal function parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

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

Let us take couple of examples to describe the above mentioned statement practically

package mainimport (
"encoding/json"
"log"
)
func main() {
jsonString:=`{"product":"car","color":"white","seats":5,"convertible":true, "cost":null}`
var v interface{}
err := json.Unmarshal([]byte(jsonString), &v)
if err != nil {
log.Println(err)
}
log.Printf("interface value type for json object: %T", v)switch t := v.(type) {

case map[string]interface{}:
log.Printf("interface value type for JSON string: %T", t["product"])
log.Printf("interface value type for JSON number: %T", t["seats"])
log.Printf("interface value type for JSON boolean:%T", t["convertible"])
log.Printf("interface value type for JSON null: %T", t["cost"])
}
}

Here in the above program we tried unmarshalling the json object(jsonString) to an interface value(v). After that we are printing the interface value types for different JSON types. When we execute the program, we get the following result

output:
interface value type for json object: map[string]interface {}
interface value type for JSON string: string
interface value type for JSON number: float64
interface value type for JSON boolean:bool
interface value type for JSON null: <nil>

package mainimport (
"encoding/json"
"log"
)
func main() {
jsonArray:=`[{"product":"car","color":"white","seats":5,"convertible":true, "cost":null}]`
var v interface{}
err := json.Unmarshal([]byte(jsonArray), &v)
if err != nil {
log.Println(err)
}
log.Printf("interface value type for json array: %T", v)
}

For the above example, the execution result will be

output:
interface value type for json array: []interface {}

Reference: https://pkg.go.dev/encoding/json#Unmarshal

Thank you for reading! If you like this, follow and subscribe my profile for more stories

--

--

Sai

Full Stack Developer with Backend focus |Golang enthusiast | Golang Developer