0

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)
}
1
  • 1
    Do not ignore errors. The program panics because you didn’t handle the error from Unmarshal.
    – JimB
    Mar 14, 2022 at 18:15

1 Answer 1

5

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

1
  • 2
    To check for the error, you could assign the result of json.Unmarshal into a variable and check / print its value.
    – FirstOne
    Mar 14, 2022 at 17:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.