Golang access nested element on Json

Issue

I have the following golang code which trying to access elements on array my expectation to print bxar ,but it throw error any idea?

package main
    
import (
    "encoding/json"
    "fmt"
)

type Data struct {
    Args struct {
        Foo string
    }
}

func main() {
    in := `[{"args": {"foo": "bar"}},{"args": {"foo": "bxar"}}]}`

    var d []Data
    json.Unmarshal([]byte(in), &d)

    fmt.Println("Foo:", d[1].Args.Foo)
    //fmt.Printf("Result: %+v", d)
}

Solution

The reason it does not work is a typo. There is one too many } in your JSON:

Before:

`[{"args": {"foo": "bar"}},{"args": {"foo": "bxar"}}]}`

After:

`[{"args": {"foo": "bar"}},{"args": {"foo": "bxar"}}]`

See this playground: https://go.dev/play/p/sL8Cx8lF6WR

Answered By – Jens

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.