...

/

Decoding with JSON

Decoding with JSON

This lesson provides a detailed explanation on decoding data with JSON by providing coded examples.

Decoding arbitrary data

The json package uses map[string]interface{} and []interface{} values to store arbitrary JSON objects and arrays; it will happily unmarshal any valid JSON blob into a plain interface{} value.

Consider this JSON data, stored in the variable b:

b := []byte(`{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`)

Without knowing this data’s structure, we can decode it into an interface{} value with Unmarshal:

var f interface{}
err := json.Unmarshal(b, &f)

At this point, the value in f would be a map, whose keys are strings and whose values are themselves stored as empty interface values:

map[string]interface{}{
  "Name": "Wednesday",
  "Age": 6,
 
...