Search⌘ K

Decoding with JSON

Explore decoding JSON data in Go by handling arbitrary data with interfaces and map types, struct-based unmarshaling, and streaming using encoders and decoders. Understand techniques to access and manipulate JSON data safely and flexibly.

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,
  "Parents": []interface{}{
    "Gomez",
    "Morticia",
  },
}

To access this data we can use a type assertion to access f's underlying map[string]interface{}:

m := f.(map[string]interface{})
...