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

Golang access nested element on Json

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 :

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

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

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