CodeBlanks Logo Icon CodeBlanks

JSON and map

Learn map[string]interface{} for dynamic JSON.

JSON and maps

For JSON whose structure isn't known in advance, map[string]any can be used. The decoded value types are fixed: object → map[string]any, array → []any, number → float64, text → string.

var m map[string]any
json.Unmarshal([]byte(`{"ad":"Ada","yas":36}`), &m)
yas := m["yas"].(float64)  // not int!

Since type assertions are needed everywhere, a struct is preferred when possible.

json.RawMessage

To postpone decoding a field, use json.RawMessage; for example, events decoded into different structs depending on a tur field:

type Olay struct {
    Tur  string          `json:"tur"`
    Veri json.RawMessage `json:"veri"`
}

switch o.Tur {
case "siparis":
    var s Siparis
    json.Unmarshal(o.Veri, &s)
}

This builds a structure that is both flexible and type-safe.

Practice Dynamic JSON

Decode the text {"ad":"Ada","diller":["go","sql"],"yas":36} into a map[string]any. Assert yas as float64 and diller as []any, then print the age converted to int and the number of languages.

Starter code

main.go
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var m map[string]any
    if err := json.Unmarshal([]byte(`{"ad":"Ada","diller":["go","sql"],"yas":36}`), &m); err != nil {
        fmt.Println(err)
        return
    }
    yas := m["yas"].(float64)
    diller := m["diller"].([]any)
    fmt.Println(int(yas), len(diller))
}

Expected output

36 2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the Go type of the number <code>36</code> decoded into a <code>map[string]any</code>?

  • int
  • int64
  • string
  • float64 Correct answer

Explanation: JSON has no integer/decimal distinction; with an any target the json package makes every number float64. For large integers use Decoder.UseNumber.

2 Postpone decoding

Question
type Mesaj struct {
    Tur  string          `json:"tur"`
    Govde json.____ `json:"govde"`
}
Answer
type Mesaj struct {
    Tur  string          `json:"tur"`
    Govde json.RawMessage `json:"govde"`
}

Explanation: RawMessage stores the field's raw JSON bytes without decoding them.

3 JSON → any

Term Meaning
{...} map[string]any
[...] []any
36 float64
"metin" string

All lessons in Intermediate