Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JSON Marshal and Unmarshal with GO

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading