JSON Marshal and Unmarshal with GO

Issue

Why my unmarshalling is returning an empty Person-struct, in this context?

How can I make this program work as expected? E.i., successfully Marshalling and Unmashalling my made-up data.

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    name  string
    addr  string
    phone string
}

func main() {
    p1 := Person{name: "joe", addr: "a st.", phone: "123"}

    barr, err := json.Marshal(p1)
    fmt.Println(err)
    fmt.Println("byte array (barr):", barr, "\t person 1 (p1) in Go:", p1)

    var p2 Person
    err2 := json.Unmarshal(barr, &p2)
    fmt.Println("person 2 (p2) in Go:", p2, "error:", err2)
}
: <nil>
: byte array (barr): [123 125]   person 1 (p1) in Go: {joe a st. 123}
: person 2 (p2) in Go: {  } error: <nil>

Solution

You have to export the fields if you want them to be marshaled. See here:

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name  string `json:"name"`
    Addr  string `json:"addr"`
    Phone string `json:"phone"`
}

func main() {
    p1 := Person{Name: "joe", Addr: "a st.", Phone: "123"}

    barr, err := json.Marshal(p1)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(barr))
}

output:

{"name":"joe","addr":"a st.","phone":"123"}

Notice, you can use the struct tags, if you still need the keys to be lower case.

run in playground

Answered By – theherk

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.