Claudio Merli
Claudio Merli

Reputation: 101

How to unmarshal nested struct JSON

I'm studying about JSON encoding and decoding, but I'm stuck on nested struct unmarshaling.

I tried to declare both the children struct as external type and explicit struct in the parent as follow:

type WorkingSession struct {
    Project Project `json:"project"`
    Hours int    `json:"hours"`
    Date  string `json:"date"`
    Nested struct{
        NestedField string `json:"nested_field"`
    } `json:"nested"`
}

type Project struct {
    Name string `json:"name"`
}

But when I execute my main:

func main() {
    document:= []byte(`
        {
            "project " : {"name" : "Project 1"},
            "hours" : 4,
            "date" : "2019-11-03",
            "nested" : {"nested_field" : "test"}
        }
    `)

    var ws WorkingSession

    err := json.Unmarshal(document, &ws)

    log.Println(ws)
    if err != nil {
        log.Fatal(err.Error())
    }

}

It does not print the project nested fields:

2019/11/03 11:24:04 {{} 4 2019-11-03 {test}}

What is wrong?

Upvotes: 0

Views: 155

Answers (1)

Masudur Rahman
Masudur Rahman

Reputation: 1683

You have another typo in your project key.

You have a space in "project ". Remove the space and it will work fine.

document:= []byte(`
    {
        "project" : {"name" : "Project 1"},
        "hours" : 4,
        "date" : "2019-11-03",
        "nested" : {"nested_field" : "test"}
    }
`)

Upvotes: 1

Related Questions