How to decode json into structs

You must Uppercase struct fields:

type MxRecords struct {
    Value    string `json:"value"`
    Ttl      int    `json:"ttl"`
    Priority int    `json:"priority"`
    HostName string `json:"hostName"`
}

type Data struct {
    MxRecords []MxRecords `json:"mxRecords"`
}

http://play.golang.org/p/EEyiISdoaE


The encoding/json package can only decode into exported struct fields. Your Data.mxRecords member is not exported, so it is ignored when decoding. If you rename it to use a capital letter, the JSON package will notice it.

You will need to do the same thing for all the members of your MxRecords type.


As per the go documentaiton about json.Unmarshal, you can only decode toward exported fields, the main reason being that external packages (such as encoding/json) cannot acces unexported fields.

If your json doesn't follow the go convention for names, you can use the json tag in your fields to change the matching between json key and struct field.

Exemple:

package main

import (
    "fmt"
    "encoding/json"
)

type T struct {
    Foo  string `json:"foo"`
    priv string `json:"priv"`
}

func main() {
    text := []byte(`{"foo":"bar", "priv":"nothing"}`)
    var t T
    err := json.Unmarshal(text, &t)
    if err != nil {
        panic(err)
    }
    fmt.Println(t.Foo) // prints "bar"
    fmt.Println(t.priv) // prints "", priv is not exported
}

Tags:

Json

Go